带有两个可选参数的 asp mvc 路由 [英] asp mvc routing with two optional parameters

查看:23
本文介绍了带有两个可选参数的 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 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆