简体   繁体   中英

ASP.NET MVC Attribute Routing - parameter is always null

Recently I have faced the following issue. Let's suppose that we have following controller with GET method inside:

[RoutePrefix("admin-panel")]
public class AdminPanelController : Controller
{
   [Route("places/edit/{placeId}")]
   public ActionResult EditPlace(int? placeId)
   {
     return View("EditPlace", new EditPlaceViewModel(...));
   }
}

Now we can access this method by url:

(...)/admin-panel/places/edit/123

The problem is that the placeId parameter is always null .

If I change the EditPlace method routing rule to following:

[RoutePrefix("admin-panel")]
public class AdminPanelController : Controller
{
   [Route("places/{placeId}/edit")]
   public ActionResult EditPlace(int? placeId)
   {
     return View("EditPlace", new EditPlaceViewModel(...));
   }
}

Everything starts working properly - placeId parameter is being passed successfuly.

What am I missing here? Why can't I use first solution?

Thanks in advance!

@update

OK, I've missed that I have the POST methods with the same routing rules which look like:

[HttpPost]
[Route("places/edit/{placeId}")]
[MultipleSubmitButton(Name = "action", Argument = "NextEditStep")]
public ActionResult NextEditStep(int? placeId, EditPlaceViewModel model)
{
    // do some operations with posted model
    return View("EditPlace", new EditPlaceViewModel(...));
}

[HttpPost]
[Route("places/edit/{placeId}")]
[MultipleSubmitButton(Name = "action", Argument = "PreviousEditStep")]
public ActionResult PreviousEditStep(int? placeId, EditPlaceViewModel model)
{
    // do some operations with posted model
    return View("EditPlace", new EditPlaceViewModel(...));
}

If I comment them out, the problem walk away, but to be honest - I need it due to form generating. Is there any chance to have those 3 methods with the same routing rules?

I have similar controller with similar 3 methods (1 GET & 2 POSTS) but they do not have any route parameters. Anyway this routing works great and behaves as expected. The only difference is that the first one have route parameters and the second does not.

[Route("places/edit/{placeId: int}")]

尝试这个

It's possible to use optional parameters in route, like this:

[Route("places/edit/{placeId?}")]

(edit) https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/#optionals-and-defaults

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM