首页 文章

动态MVC路由:动作名称

提问于
浏览
0

我有控制器名称:关于和操作名称:索引 . 但我希望URL像这样(动作名称将动态)

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

Routing

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

Controller

public class AboutController : Controller
    {
        //
        // GET: /About/

        public ActionResult Index(string name)
        {

            return View();
        }

    }
}

View

@{
    ViewBag.Title = "Index";
}

<h2>Index About</h2>

3 回答

  • 0

    这应该工作 .

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

    确保您的默认路线存在,并在关于路线之后

  • 0
    routes.MapRoute(
        name: "About",
        url: "about/{name}/{id}",
        defaults: new { controller = "About", action = "Index", id=UrlParameter.Optional}
    
  • 4

    您可以将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)
    

相关问题