trouble sending message to the view from controller
-
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.
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!
-
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!
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.
-
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.
In MVC , ViewBag , ViewData and TempDate are preferred than Session. In your case , try TempData.
-
In MVC , ViewBag , ViewData and TempDate are preferred than Session. In your case , try TempData.
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.
-
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.
Can you show us the code for
return RedirectToAction("UploadFiles");
? Are you able to see the Session['msg'] in there before View.
-
Can you show us the code for
return RedirectToAction("UploadFiles");
? Are you able to see the Session['msg'] in there before View.
RedirectToAction is a built-in method provided by the MVC framework, it's not something he has written himself.
-
RedirectToAction is a built-in method provided by the MVC framework, it's not something he has written himself.
I meant the
"UploadFiles"
where he is redirecting to.
-
Can you show us the code for
return RedirectToAction("UploadFiles");
? Are you able to see the Session['msg'] in there before View.
Yes
-
I meant the
"UploadFiles"
where he is redirecting to.
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)
-
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)
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