Question

Converting an MVC 3 app to MVC 5 and relying exclusively on Attribute Routing. All is good but I am unable to define a route for a controller method that accepts a (not so) complex object as a parameter.

If I omit the parameter in the route, my controller/method is never invoked and I receive a 404 (as I would expect). When I include the viewModel parameter as part of the route, my method is invoked but the parameter is always null.

This code worked fined before with "classic" routing and no specific route was needed to model bind my viewModel parameter. I never defined it as part of any route other than including the controller and method names. The view is unchanged.

[RoutePrefix("Text")]
[Route("{action}")]
public class TextController : Controller
{
    [HttpGet]
    [Route("{jobTextID}")]
    public ViewResult Edit(Guid jobTextID)
    {
        // this (get) works fine
    }

    [HttpPost]
    [Route("{viewModel}"]
    public RedirectToRouteResult Edit(TextEditViewModel viewModel)
    {
        // viewModel is always null
    }
}
Was it helpful?

Solution

I think you should add the id to the POST action:

[HttpPost]
[Route("{jobTextID}")]
public RedirectToRouteResult Edit(Guid jobTextID, TextEditViewModel viewModel) { }

The resource is identified by the URL, not by a parameter in the body of the request. Use jobTextID to retrieve the entity from the database and ignore the id from the viewModel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top