Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. trouble sending message to the view from controller

trouble sending message to the view from controller

Scheduled Pinned Locked Moved ASP.NET
databasehelpasp-netsysadmindebugging
12 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F F ES Sitecore

    This might be a caching issue, so when the browser requests the UploadFiles page it shows the cached version rather than asking for a new version so your message isn't there. If that's the case you can "fix" this by adding something random to the url

    return RedirectToAction("UploadFiles", new { r = DateTime.Now.Ticks.ToString() });

    that will add an "r" param with a pseudo-random number forcing the browser to get an updated version of the page.

    H Offline
    H Offline
    Hamiltonian13
    wrote on last edited by
    #3

    Thanks for your answer. Unfortunately it did not solve my issue. The code seems to be operating as expected when using breakpoints, it is getting to the RedirectToAction line but no reload. Refresh browser and message is there!

    F 1 Reply Last reply
    0
    • H Hamiltonian13

      Thanks for your answer. Unfortunately it did not solve my issue. The code seems to be operating as expected when using breakpoints, it is getting to the RedirectToAction line but no reload. Refresh browser and message is there!

      F Offline
      F Offline
      F ES Sitecore
      wrote on last edited by
      #4

      Use the network tools of the browser to examine the network traffic and look at the statuses etc to see if it really is getting a cached version or not and to see if the redirect is happening etc.

      1 Reply Last reply
      0
      • H Hamiltonian13

        Hi all, I am having trouble sending a success/fail message to a view from my controller. I have a file upload section of my website. User chooses file, presses upload button and file is saved in a folder. My Controller code:

        public ActionResult UploadFiles(int? id)
        {
        CI cI = db.DataBase.Find(id);
        foreach (string upload in Request.Files)
        {

                    if (Request.Files\[upload\].FileName != "")
                        
                    {
                        string path = Server.MapPath(@"/App\_Data/uploads/" + id + "/");
                        string filename = Path.GetFileName(Request.Files\[upload\].FileName);
                        Response.Write(path);
                 
                        bool check = System.IO.File.Exists(Path.Combine(path, filename));
                        
        
                        //Check if the filename exists or not, send message and refresh
                        if (check==true)
                        {
                            Session\["msg"\] = "File with the same name already exists - Choose another file or change the file name";
                            System.Diagnostics.Debug.Write("file exists");
                            return RedirectToAction("UploadFiles");
                        }
        
                        if (check == false)
                        {
                            Session\["msg"\] = "Successfull Upload";
                            Request.Files\[upload\].SaveAs(Path.Combine(path, filename));
                            System.Diagnostics.Debug.Write("Upload success");
                            return RedirectToAction("UploadFiles");
                        }
                    }
                }
        
                         return View("Upload");
            }
        

        Then I am calling the message in my view using:

        @Session["msg"];

        The code is working for the most part i.e. it will check if the file exists/doesn't correctly and print the correct message to the output. My problem is getting the message to the view. If I manually refresh the page my message gets to the view. So that tells me I am making a mistake with how I am redirecting. I am quite new to Mvc so I can't identify the problem. Any help would be greatly appreciated.

        J Offline
        J Offline
        John C Rayan
        wrote on last edited by
        #5

        In MVC , ViewBag , ViewData and TempDate are preferred than Session. In your case , try TempData.

        H 1 Reply Last reply
        0
        • J John C Rayan

          In MVC , ViewBag , ViewData and TempDate are preferred than Session. In your case , try TempData.

          H Offline
          H Offline
          Hamiltonian13
          wrote on last edited by
          #6

          Thanks for your reply. I have been using all three ViewBag, TempData & Session while testing but to no avail. I agree Temp data is the best here. From my little knowledge, I have read that it is best practice to use TempData for redirects.

          J 1 Reply Last reply
          0
          • H Hamiltonian13

            Thanks for your reply. I have been using all three ViewBag, TempData & Session while testing but to no avail. I agree Temp data is the best here. From my little knowledge, I have read that it is best practice to use TempData for redirects.

            J Offline
            J Offline
            John C Rayan
            wrote on last edited by
            #7

            Can you show us the code for

            return RedirectToAction("UploadFiles");

            ? Are you able to see the Session['msg'] in there before View.

            F H 2 Replies Last reply
            0
            • J John C Rayan

              Can you show us the code for

              return RedirectToAction("UploadFiles");

              ? Are you able to see the Session['msg'] in there before View.

              F Offline
              F Offline
              F ES Sitecore
              wrote on last edited by
              #8

              RedirectToAction is a built-in method provided by the MVC framework, it's not something he has written himself.

              J 1 Reply Last reply
              0
              • F F ES Sitecore

                RedirectToAction is a built-in method provided by the MVC framework, it's not something he has written himself.

                J Offline
                J Offline
                John C Rayan
                wrote on last edited by
                #9

                I meant the

                "UploadFiles"

                where he is redirecting to.

                H 1 Reply Last reply
                0
                • J John C Rayan

                  Can you show us the code for

                  return RedirectToAction("UploadFiles");

                  ? Are you able to see the Session['msg'] in there before View.

                  H Offline
                  H Offline
                  Hamiltonian13
                  wrote on last edited by
                  #10

                  Yes

                  1 Reply Last reply
                  0
                  • J John C Rayan

                    I meant the

                    "UploadFiles"

                    where he is redirecting to.

                    H Offline
                    H Offline
                    Hamiltonian13
                    wrote on last edited by
                    #11

                    Hi everyone, Firstly, thanks for trying to help me out with this. I have fixed the issue. The problem was not in the controller, it was in fact the view. My problem is I am completely new to this type of coding, In fact, up to a couple of months ago, the only programming I had dabbled in was matlab for scientific analysis purposes. I probably should spend more time learning the basics, but as I have absolutely no patience, I have decided to build first and analyse later. I would appreciate it if I could get some help understanding where I went wrong. The view I was using was utilizing Ajax. Data was added to the form data collection and then passed to the controller via Ajax call. The View:

                    @{
                    ViewBag.Title = "Upload";
                    }

                    Upload

                    $(document).ready(function () {
                        $(‘#btnUploadFile’).on(‘click’, function () {
                            var data = new FormData();
                            var files = $("#fileUpload").get(0).files;
                            // Add the uploaded image content to the form data collection
                            if (files.length > 0) {
                                data.append("UploadedImage", files\[0\]);
                            }
                            // Make Ajax request with the contentType = false, and procesDate = false
                            var ajaxRequest = $.ajax({
                                type: "POST",
                                url: "",
                                contentType: false,
                                processData: false,
                                data: data
                            });
                            ajaxRequest.done(function (xhr, textStatus) {
                                // Do other operation
                            });
                        });
                    });
                    

                    @Html.ActionLink("Documents", "Downloads")

                        @TempData\["msg"\] 
                    

                    I had a feeling (Uneducated guess!)that using the Ajax request was the problem so I changed my approach. I used the Html.BeginForm() extension method I changed my view to:

                    @using (Html.BeginForm("UploadFiles", "CIsAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
                    {

                    }
                    @Html.ActionLink("Documents", "Downloads")

                        @TempData\["msg"\] 
                    

                    Can someone explain in simple terms, what the issue was? FYI, this is my controller code:

                    public ActionResult UploadFiles(int? id,string msg)

                    J 1 Reply Last reply
                    0
                    • H Hamiltonian13

                      Hi everyone, Firstly, thanks for trying to help me out with this. I have fixed the issue. The problem was not in the controller, it was in fact the view. My problem is I am completely new to this type of coding, In fact, up to a couple of months ago, the only programming I had dabbled in was matlab for scientific analysis purposes. I probably should spend more time learning the basics, but as I have absolutely no patience, I have decided to build first and analyse later. I would appreciate it if I could get some help understanding where I went wrong. The view I was using was utilizing Ajax. Data was added to the form data collection and then passed to the controller via Ajax call. The View:

                      @{
                      ViewBag.Title = "Upload";
                      }

                      Upload

                      $(document).ready(function () {
                          $(‘#btnUploadFile’).on(‘click’, function () {
                              var data = new FormData();
                              var files = $("#fileUpload").get(0).files;
                              // Add the uploaded image content to the form data collection
                              if (files.length > 0) {
                                  data.append("UploadedImage", files\[0\]);
                              }
                              // Make Ajax request with the contentType = false, and procesDate = false
                              var ajaxRequest = $.ajax({
                                  type: "POST",
                                  url: "",
                                  contentType: false,
                                  processData: false,
                                  data: data
                              });
                              ajaxRequest.done(function (xhr, textStatus) {
                                  // Do other operation
                              });
                          });
                      });
                      

                      @Html.ActionLink("Documents", "Downloads")

                          @TempData\["msg"\] 
                      

                      I had a feeling (Uneducated guess!)that using the Ajax request was the problem so I changed my approach. I used the Html.BeginForm() extension method I changed my view to:

                      @using (Html.BeginForm("UploadFiles", "CIsAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
                      {

                      }
                      @Html.ActionLink("Documents", "Downloads")

                          @TempData\["msg"\] 
                      

                      Can someone explain in simple terms, what the issue was? FYI, this is my controller code:

                      public ActionResult UploadFiles(int? id,string msg)

                      J Offline
                      J Offline
                      John C Rayan
                      wrote on last edited by
                      #12

                      The difference between the Ajax and Submitting the form is that in Ajax , it is Async call and it does not reload your view. The ajax call receives the response from your action (URL) and does the update with the controls in the view based on your code. Whereas in form submission , the action is called with post data and the view is reloaded again with action response. So you have to check how you update the response message in your view based on these two different behaviours. Hope this helps

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups