ASP.NET MVC 5 generates right url but executes wrong Action

I got a custom routes created for 2 different actions in same controller:

routes.MapRoute(
    name: "editEquivPack",
    url: "equivpacks/{id}/{ecommerceid}",
    defaults: new { controller = "EquivPacks", action = "Edit" }
);
routes.MapRoute(
    name: "addEquivPack",
    url: "equivpacks/add/{ecommerceid}",
    defaults: new { controller = "EquivPacks", action = "Add" }
);

In a

URL.RouteURL("addEquivPack", ecommerceid = Model.EcommerceID) 

it generates a correct URL:

http://localhost:53365/EquivPacks/Add/1

But when i try to navigate there, it sends me a error message:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32, Int32)' in 'XXXXXXX.Controllers.EquivPacksController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

It seems that it executes Edit action and not Add action that is the action configured in route map.

How can i fix it?


The order of route definitions is important and the first match wins. Your first route definition ( editEquivPack ) means match a url containing 3 segments, where the first segment is "equivpacks".

Your url of ../EquivPacks/Add/1 matches that, so it then calls the Edit() method and passes a value of "Add" to your int id parameter in that method (which cannot be bound to an int , hence the error).

You need to change the order of your routes so that the addEquivPack route is before the editEquivPack route.

链接地址: http://www.djcxy.com/p/39230.html

上一篇: Dialog在Windows Mobile上不能关闭

下一篇: ASP.NET MVC 5生成正确的URL但执行错误的操作