0

I have an MVC 4 app and I am using a RESTful methodology for my URLs. I have the following routes registered in my app (along with others that are not relevant to my question:

    //EDIT
    routes.MapRoute(alias + "_EDIT", alias + "/{id}/edit",
                    new { controller = controllerName, action = "edit" },
                    new { httpMethod = new RestfulHttpMethodConstraint(HttpVerbs.Get) });

    //PUT (update)
    routes.MapRoute(alias + "_PUT", alias + "/{id}",
                    new { controller = controllerName, action = "update" },
                    new { httpMethod = new RestfulHttpMethodConstraint(HttpVerbs.Put) });

I have the following methos in my controller mapping to these routes:

public override ActionResult Edit(int id)
{...}

public override ActionResult Update(RequestEditViewModel userModel)
{
   if (!ModelState.IsValid)
   {
    //do some stuff to ensure lookups are populated
    ...
        return View("Edit", userModel);
   }
}

In my app when I perform a request to edit a request my URL looks like:

http://server/request/1/edit

it correctly calls the Edit method on my controller.

My Edit.cshtml uses the followng to ensure the Update method is called on PUT:

@using (Html.BeginForm("Update", "Request"))
{
    @Html.HttpMethodOverride(HttpVerbs.Put);
    ...
}

My form is generated as follows:

<form action="/requests/71" method="post" autocomplete="off" novalidate="novalidate">
<input name="X-HTTP-Method-Override" type="hidden" value="PUT"/>
...
</form>

When I click the submit button it correctly calls my Update method.

OK...Now for the issue. If my model is NOT valid I want to return back the Edit model. As you can see in the above code but, the URL is the one called from the submit button:

http://server/request/1

not

http://server/requests/1/edit

I have tried an reviewed two other options but both of these redirect the request back through the Edit method again which adds additional overhead and also puts all the model values in the querystring which I do NOT want:

return RedirectToAction("Edit", userModel);
return RedirectToRoute("requests_Edit", userModel);

So, is there a way to just return the View as I have in my code but, ensure the URL changes back and include the "/edit"?

The only alternative I have come up with is to perform an AJAX call and put the update that way the URL never changes, but I was trying to avoid that for this form.

Jay
  • 2,644
  • 1
  • 30
  • 55
  • If possible, look into the PRG pattern for submitting forms. It works nicely in MVC. Googling 'post redirect get asp.net mvc' will have some pretty good examples. – arserbin3 May 29 '14 at 15:32

1 Answers1

0

Conceptually, you want to be doing something like a Server.Transfer (that is, making on URL appear to be another.) This discussion may be of use to you:

How to simulate Server.Transfer in ASP.NET MVC?

Community
  • 1
  • 1
jlew
  • 10,491
  • 1
  • 35
  • 58