【问题标题】:How to do MVC 4 routing with arguments and defaults如何使用参数和默认值进行 MVC 4 路由
【发布时间】:2014-12-24 20:40:01
【问题描述】:

这是我的默认路线:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }
);

我的控制器是“Home”,我的视图是“Index”,它采用默认参数:

public class HomeController : Controller
{
    public ActionResult Index(string Queue = "ALL", string Summary = "false")
    {
        ...
    }
}

我当前的网址如下所示:

http://www.example.com/?Queue=ONE&Summary=true

但我希望它被路由到这样的东西:

http://www.example.com/ONE?Summary=true

基本上是路由它,所以我不必在 URL 中使用 Queue 关键字。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 url routing url-routing


    【解决方案1】:

    如下修改你的路由定义,

     routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{Queue}",
        defaults: new { controller = "Home", action = "Index", Queue = UrlParameter.Optional }
    );
    

    【讨论】:

    • 这将在我们使用完整 URL 时起作用。如果控制器名称和操作名称未在 URL 中明确指定(由 OP example.com/ONE?Summary=true 指定),它将不起作用,我错过了什么吗?
    • 你是对的。它没有像描述的那样工作,但我尝试了这个更改 -> url: "{Queue}" (删除 {controller}/{action}/) 并且它工作了:-)
    猜你喜欢
    • 2013-01-22
    • 2011-08-01
    • 2017-01-13
    • 2012-09-12
    • 2021-04-17
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多