0

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!

GeorgiG
  • 1,018
  • 1
  • 13
  • 29

2 Answers2

2

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

Community
  • 1
  • 1
Vineet Desai
  • 872
  • 5
  • 16
  • Thanks, you're very helpful. TempData turns out to be a very useful tool and it will help me a lot along the way. – GeorgiG Apr 06 '16 at 06:18
1

Viewbag only lives for current request. You need to use TempData instead.

Please check this thread Viewbag passing value

Community
  • 1
  • 1
Ameya
  • 726
  • 6
  • 9