带有两个可选参数的asp mvc路由

asp mvc routing with two optional parameters(带有两个可选参数的asp mvc路由)

本文介绍了带有两个可选参数的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路由

基础教程推荐