开发者

Passing a parameter to an Index view

开发者 https://www.devze.com 2023-04-06 20:29 出处:网络
Pretty basic question here. How come I get a 404 error when I开发者_如何转开发 try to view /Vendors/123

Pretty basic question here. How come I get a 404 error when I开发者_如何转开发 try to view

/Vendors/123

But I can see the page if I go to

/Vendors/Index/123

Is there any way for me to make it work the first way? I'm just using the default routes being registered in Global.asax.


Because that's how the default route is defined. If you don't want to specify an actionname you could modify it like this:

routes.MapRoute(
    "Default",
    "{controller}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

This being said you probably shouldn't be doing this because now in your route you do not have the possibility to specify the action name that you wish to invoke on a given controller which means that you can only have a single action on each controller and that action would be Index. On the other hand if you wanted to do this on some specific controller you could still preserve the default route and add another one:

routes.MapRoute(
    "Vendors",
    "vendors/{id}",
    new { controller = "Vendors", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


Because in your basic routing {id} expects after action name, but you are trying to put it after controller name.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Change your rout to accept {id} just after {controller}. Just like @Darin described.

0

精彩评论

暂无评论...
验证码 换一张
取 消