简体   繁体   English

如何在MVC4中的控制器中更改参数名称?

[英]How to change parameter name in controller in MVC4?

I have a Controller like following: 我有一个如下的控制器:

public class PostsController : Controller
{
    public ActionResult Index(int CategoryID)
    {
        return Content(CategoryID.ToString());
    }
}

And my router is: 我的路由器是:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
 }

I wants add a MapRoute into RegisterRoutes like this: 我想像这样将MapRoute添加到RegisterRoutes中:

routes.MapRoute(
    name: "Posts",
    url: "Posts/{action}/{CategoryID}",
    defaults: new { controller = "Posts", action = "Index", CategoryID = UrlParameter.Optional }
);

I go to /Posts/Index/1 url but I give following error: 我转到/ Posts / Index / 1网址,但出现以下错误:

The parameters dictionary contains a null entry for parameter 'CategoryID' of non-nullable type 'System.Int32' 参数字典包含非空类型“ System.Int32”的参数“ CategoryID”的空条目

Note: in controller if I change CategoryID to id problem solved, and it worked! 注意:在控制器中,如果我将CategoryID更改为id,则问题已解决,并且可以正常工作!

As @Davide Icardi said, you need to place your new route above the default route. 正如@Davide Icardi所说,您需要将新路线放置在默认路线上方。

Routes are evaluated from first to last; 从头到尾评估路线; the first one to match will be used. 将使用第一个匹配的内容。 Placing the route specific to the Posts controller at the top of the list will guarantee that it is matched before the default route. 将特定于Posts控制器的路由放在列表顶部将确保在默认路由之前匹配该路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从MVC4中的URL中删除控制器名称 - Removing a controller name from a URL in MVC4 如何通过单击编辑按钮在 mvc4 devExpress 中使用 SetDataItemTemplateContent 将参数从 gridview 传递到 controller? - How to pass Parameter from gridview to controller using SetDataItemTemplateContent in mvc4 devExpress by clicking Edit Button? 我如何使用 datapost 将参数从 jqgrid 传递到 controller(使用 MVC4 和 asp.net) - how can i pass parameter from jqgrid to controller with datapost (using MVC4 and asp.net ) 与区域同名的控制器 - Asp.Net MVC4 - Controller with same name as an area - Asp.Net MVC4 MVC4-值不能为null。 参数名称:来源 - MVC4 - Value can not be null. Parameter name: source 通过MVC4控制器向Signalr发送数据库更改通知 - Database change notification to signalr via mvc4 controller 如何将xml从控制器传递到mvc4中的其他控制器 - how to pass xml from controller to other controller in mvc4 使用mvc4在.net服务器上保存文件时更改名称 - Change The name While saving the File on .net server using mvc4 MVC控制器路由,在url中更改控制器名称 - MVC Controller routing, change the name of controller in url 如何在URL中更改ASP.NET MVC控制器名称? - How to Change ASP.NET MVC Controller Name in URL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM