問題描述
您好,當兩個參數都是可選的時,我如何映射 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路由的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!