Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i keep my url when my validation fail in asp.net mvc controller action

Tags:

c#

asp.net-mvc

if i start off on a Detail page:

http:\\www.mysite.com\App\Detail

i have a controller action called Update which normally will call redirectToAction back to the detail page. but i have an error that is caught in validation and i need to return before redirect (to avoid losing all of my ModelState). Here is my controller code:

 public override ActionResult Update(Application entity)
    {
        base.Update(entity);
        if (!ModelState.IsValid)
        {
            return View("Detail", GetAppViewModel(entity.Id));
        }
      return RedirectToAction("Detail", new { id = entity.Id }) 

but now I see the view with the validation error messages (as i am using HTML.ValidationSummary() ) but the url looks like this:

http:\\www.mysite.com\App\Update

is there anyway i can avoid the URL from changing without some hack of putting modelstate into some temp variables? Is there a best practice here as the only examples i have seen have been putting ModelState in some tempdata between calling redirectToAction.

like image 990
leora Avatar asked Jul 20 '10 10:07

leora


Video Answer


1 Answers

As of ASP.NET MVC 2, there isn't any such API call that maintains the URL of the original action method when return View() is called from another action method.

Therefore as such, the recommended solution and a generally accepted convention in ASP.NET MVC is to have a corresponding, similarly named action method that only accepts a HTTP POST verb. So in your case, having another action method named Detail like so should solve your problem of having a different URL when validation fails.

[HttpPost]
public ActionResult Detail(Application entity)
{
    base.Update(entity);
    if (ModelState.IsValid)
    {
        //Save the entity here
    }
   return View("Detail", new { id = entity.Id });
}  

This solution is in line with ASP.NET MVC best practices and also avoids having to fiddle around with modestate and tempdate.

In addition, if you haven't explored this option already then client side validation in asp.net mvc might also provide for some solution with regards to your URL problem. I emphasize some since this approach won't work when javascript is disabled on the browser.

So, the best solution would be have an action method named Detail but accepting only HTTP POST verb.

like image 96
Bikal Lem Avatar answered Nov 04 '22 20:11

Bikal Lem