可以重命名MVC路由中的ACTION参数吗?

时间:2013-07-15 23:27:23

标签: asp.net-mvc url-routing

我的RouteConfig,cs文件中有以下路径:

routes.MapRoute(
    name: "SectionHomePage",
    url: "{SectionType}/{SectionID}",
    constraints: new { SectionType = @"(Books|Cinema|Collections|Games)" },
    defaults: new { controller = "SectionHomePageController" }
    );

如果可能,我想要做的是将action参数重命名为SectionType或以某种方式将SectionType分配给action参数。 (我知道我可以将SectionType重命名为action,但为了便于阅读,我想保留命名。

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FFInfo.WebUI.Controllers
{
    public class SectionHomePageController : Controller
    {
        // GET: /SectionHomePage/
        public ActionResult Games()
        {
            //ViewBag.Head = RouteData.Values["id"];
            return View();
        }
    }
}

错误:

  

RouteData必须包含名为“action”且非空的项目   字符串值。

2 个答案:

答案 0 :(得分:0)

需要采取措施,但您可以在路线中设置操作

routes.MapRoute(
    name: "SectionHomePage",
    url: "{SectionType}/{SectionID}",
    constraints: new { SectionType = @"(Books|Cinema|Collections|Games)" },
    defaults: new { controller = "SectionHomePageController", action="Section" }
);

这假设您有一个SectionHomePageController,其操作类似于此

public ActionResult Section(string sectionType, int sectionId) 
{
    // can use a switch...case instead
    if (sectionType == "Books")
       return Books(sectionId);
}
public ActionResult Books(int sectionId)
{
    var model = GetBooksModel(); // load stuff
    return View("Books", model); // Set view and provide model
}

或者你可以

routes.MapRoute(
    name: "SectionHomePage",
    url: "{action}/{SectionID}",
    constraints: new { action = @"(Books|Cinema|Collections|Games)" },
    defaults: new { controller = "SectionHomePageController" }
);

使用actionResults

public ActionResult Books(int sectionId) 
{
    var model = GetBooksModel(); // load stuff
    return View("Books", model); // Set view and provide model
}

public ActionResult Cinema(int sectionId) 
{
    ...
}

答案 1 :(得分:0)

无法重命名ACTION元素。