문제

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
    }
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top