您好如果两个参数都是可选的,我如何映射网址 ../公司/结果/值/ ID ?
公司是控制器,结果是动作,值和id是可选参数。在我的表单上是一个值的文本框和一个id的选择列表。用户可以选择两个或每个中的一个来搜索。试过这样的事情但是当一个可选参数(例如值)缺失时无法处理,例如../Companies/Results/ / id
routes.MapRoute(
"Company+Profession", // Route name
"{action}/{value}/{profId}", // URL with parameters
new { controller = "Companies", action = "Index", value = UrlParameter.Optional, profId = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
答案 0 :(得分:9)
您不能拥有包含两个可选参数的路由,由于您描述的问题,只有最后一个参数可以精确选择。我建议您使用value
的默认参数,例如 byid ,并在此人选择专业时使用此参数。
我假设你是通过javascript构建URL,因为使用GET表单操作会导致参数名称被添加到URL。在这种情况下,当文本框为空时,只需插入默认的 byid 。
更新您的路线以包含默认路线,以便您生成的所有网址都有效。有关处理生成具有两个“可选”参数的URL的替代方法,请参阅Phil Haack的blog post。
// used when both parameters are specified
routes.MapRoute(
"Company+Profession", // Route name
"{action}/{value}/{profId}", // URL with parameters
new { controller = "Companies", action = "Index", value ="byid", profId = UrlParameter.Optional } // Parameter defaults
);
答案 1 :(得分:1)
谢谢大家,刚刚发现整数的路由约束。所以摆弄一些路线组合似乎按照我想要的方式工作:
routes.MapRoute(
"Detail", // Route name
"{action}/{value}", // URL with parameters
new { controller = "Companies", action = "Detail" }, // Parameter defaults
new { value = @"\d+" } //integer only
);
routes.MapRoute(
"Company + Profession", // Route name
"{action}/{value}/{profId}", // URL with parameters
new { controller = "Companies", action = "Results" }, // Parameter defaults
new { profId = @"\d+" } //integer only
);
routes.MapRoute(
"Profession", // Route name
"{action}/{profId}", // URL with parameters
new { controller = "Companies", action = "Results"}, // Parameter defaults
new {profId = @"\d+" } //integer only
);
routes.MapRoute(
"Company", // Route name
"{action}/{value}", // URL with parameters
new { controller = "Companies", action = "Results" } // Parameter defaults
);
routes.MapRoute(
"RootFolder", // Route name
"{action}/{value}", // URL with parameters
new { controller = "Companies", action = "Index", value = UrlParameter.Optional } // Parameter defaults
);
答案 2 :(得分:0)
我不确定,因为我现在没有在哪里尝试这个,但这是我的建议
routes.MapRoute(
"Company+Profession", // Route name
"Companies/{action}/value-{value}/id-{profId}", // URL with parameters
new { controller = "Companies", action = "Index", value = UrlParameter.Optional, profId = UrlParameter.Optional } // Parameter defaults
);