【问题标题】:Can the ACTION parameter in MVC Routing be renamed?MVC Routing中的ACTION参数可以重命名吗?
【发布时间】:2013-10-19 06:33:45
【问题描述】:

我的 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' 的项目,且该项目具有非空 字符串值。

【问题讨论】:

  • 我没关注,到底是什么问题? Wat 是您当前的结果,您想要的结果是什么?
  • 期望的结果是,如果有人访问 mysite.com/Games/GameID,他们将收到 SectionHomePageController 的 Games 操作,并将 GameID 作为传递给它的参数。当前结果是找不到404文件(大概是因为没有定义action参数)
  • 请更新您的代码并包含您的控制器和您视图中的操作链接,以便我们查看路由的整个过程。
  • 添加了控制器和视图代码,不知道你所说的actionlinks是什么意思,如果你说的是生成URL的页面没有,我只是在浏览器的地址框中输入它。
  • 你也能复制准确的错误信息吗?您可以尝试一件事:删除路由中的 SectionHomePageController 并将其更改为 SectionHomePage。 ASP.NET 自动添加“控制器”,它可能没有拾取它已经存在。

标签: asp.net-mvc url-routing


【解决方案1】:

动作是必需的,但是你可以在路由中设置动作

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) 
{
    ...
}

【讨论】:

  • 请重新阅读我的问题。我已经说过我知道我可以将 SectionType 重命名为 action,但我想尽量不这样做。并且添加 Section 的默认操作并不能解决任何问题,每个 SectionType 都需要它自己的视图,因此仅运行默认的 Section 并不能提供解决方案。
  • 我更新了我的答案,让每个部分都有一个视图,我提供了这些示例,因为据我所知,路线需要采取行动,您必须在 url 或默认值中指定它
【解决方案2】:

不能重命名 ACTION 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多