【问题标题】:Dynamic MVC Routing : Action name动态 MVC 路由:动作名称
【发布时间】:2013-11-19 08:50:39
【问题描述】:

我有一个名为 About 的控制器和一个名为 Index 的动作。我希望 URL 是这样的(动作名称将是动态的):

www.example.com/about/aaa
www.example.com/about/bbb
www.example.com/about/ccc

路由

routes.MapRoute(
    name: "About",
    url: "{controller}/{name}",
    defaults: new { controller = "About", action = "Index"}

控制器

public class AboutController : Controller
{
    // GET: /About/
    public ActionResult Index(string name)
    {
        return View();
    }
}

查看

@{
    ViewBag.Title = "Index";
}

<h2>Index About</h2>

【问题讨论】:

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


    【解决方案1】:

    这应该可行。

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

    确保你的默认路由存在并且在关于路由之后

    【讨论】:

    • 它不工作。无法找到该资源。说明:HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。请求的网址:/About/ip
    • @Velu 确保您的默认路线存在并且在关于路线之后。
    • 感谢它现在的工作。以前默认路由是第一个,然后我有关于路由。改变位置后它工作正常。
    • @Velu Velu,不客气。如果你能接受它作为答案,我会很高兴。
    【解决方案2】:
    routes.MapRoute(
        name: "About",
        url: "about/{name}/{id}",
        defaults: new { controller = "About", action = "Index", id=UrlParameter.Optional}
    

    【讨论】:

    • 它不工作。无法找到该资源。说明:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。请求的网址:/About/ip
    【解决方案3】:

    您可以将ActionResult 名称作为参数传递:

    public ActionResult Index(string name)
    {
        return View(name);
    }    
    
    public ActionResult First()
    {
        return View();
    }
    
    public ActionResult Second()
    {
        return View();
    }
    

    在视图中:

    @Html.ActionLink("Get Action named Firts" "Index", "Home", new {name = "First"}, null)
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2017-01-04
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2023-03-24
      • 2018-02-02
      相关资源
      最近更新 更多