Reputation: 1103
I have this neat model, which is populated on a screen and inserted to a database on successful validation. To make the web app easier to use, I make it redirect to a specific URL after it posts the data. To do that, I pass the URL as a hidden field (the URL is dynamic and depends on the Get request). Of course, on failed validation the model is returned and textboxes and other editors are repopulated, but the hidden field with the URL is not. How can I make it repopulate after validation error, without it beign the part of the model?
Here's some of my code:
-get method:
public ActionResult Create()
{
ViewBag.returnUrl = System.Web.HttpContext.Current.Request.UrlReferrer; ....
-post method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Issue_ID,Issue,Case_Status,
Issued_by,Issue_Date...,HelpDesk_Service_Request_Ticket_Number")] Case @case, string returnUrl)
.
.
.
if (ModelState.IsValid)
{
db.Cases.Add(@case);
db.SaveChanges();
if (returnUrl == null)
{
return RedirectToAction("Index");
}
else
{
return Redirect(returnUrl);
}
}
return View(@case);
Thanks in advance!
Upvotes: 0
Views: 728
Reputation: 814
Viewbag only lives for current request. You need to use TempData instead.
Please check this thread Viewbag passing value
Upvotes: 1
Reputation: 932
From you question I understand you want to pass the return url value from one action (GET) to another (POST). You can store the value in TempData
TempData["returnUrl"] = new Uri("<return url>");
and then try accessing it using
var returnUrl= TempData["returnUrl"];
Note that once the value is read from TempData
, it is automatically removed from the collection. For retaining the value you can use keep() or peek() method. Please refer a similar question answered here
Upvotes: 2