asp mvc routing with two optional parameters(带有两个可选参数的asp mvc路由)
问题描述
您好,当两个参数都是可选的时,我如何映射 url ../Companies/Results/value/id?
Hi How do I map the url ../Companies/Results/value/id when both the parameters are optional?
Companies 是控制器,Results 是操作,value 和 id 是可选参数.在我的表单上是一个值的文本框和一个 id 的选择列表.用户可以选择两者或其中之一进行搜索.尝试过这样的事情,但是当缺少可选参数之一(例如值)时无法处理,例如 ../Companies/Results//id
Companies is the controller, Results is the action, value and id are optional parameters. On my form is a textbox for value and a selectlist for an id. The user could select both or one of each to search by. Tried something like this but cant handle when one of the optional parameters, say value, is missing such as ../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
);
推荐答案
你不能有一个有两个可选参数的路由,因为你描述的问题,只有最后一个参数可以是可选的.我建议您为 value
设置一个默认参数,例如 byid,并在人们选择专业时使用它.
You can't have a route that has two optional parameters, only the last parameter can be optional precisely because of the problem you describe. I suggest that you have a default parameter for value
, like byid and use this when the person selects a profession.
我假设您是通过 javascript 构建 URL,因为使用 GET 表单操作会导致将参数名称添加到 URL.在这种情况下,当文本框为空时,只需插入默认的 byid.
I assume that you're constructing the URL via javascript, since using a GET form action would result in the parameter names being added to the URL. In this case, when the textbox is empty simply insert the default byid.
更新您的路由以包含默认值,以便您生成的任何 URL 都可以使用.请参阅 Phil Haack 的 博文 关于这一点的另一种方法来处理生成具有两个可选"参数的 URL.
Update your route to include the default so any URLs that you generate will work. See Phil Haack's blog post on this for an alternative way to handle generating URLs that have two "optional" parameters.
// 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
);
这篇关于带有两个可选参数的asp mvc路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有两个可选参数的asp mvc路由


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01