【问题标题】:MVC 3 Routing questionMVC 3 路由问题
【发布时间】:2011-09-14 01:48:00
【问题描述】:

我是 MVC 新手,如果这是一个菜鸟问题,我很抱歉:

我正在 global.asax 中设置一些自定义路由。

routes.MapRoute(
    "Choose_your_dvd_Index",
    "Choose-your-dvd",
    new  { controller = "DVD", action = "Index" }
    );

routes.MapRoute(
    "Choose_your_dvd",
    "Choose-your-dvd/{categoryName}",
    new { controller = "DVD", action = "Category" }
    );

具体来说,我将“Choose-you-dvd/{categoryName}”映射到我的 DVD 控制器, 我有以下查看结果,以及默认的“选择您的 DVD”页面。

public ViewResult Category(string categoryName)
{
    var category = (db.Categories.Where(i => i.Name == categoryName).FirstOrDefault()) ?? null;

    if (category != null)
        return View(category);

    return RedirectToRoute("Choose_your_dvd_Index");

    return View() ;
}

如果用户输入了无效的类别名称,我想将用户重定向到“Choose-your-dvd”吗? (即浏览器中的 URL 发生变化)

谢谢!

【问题讨论】:

  • 好的,我已经解决了!更改为 ActionResult,它起作用了! (丢失了第二个“return View()”!)
  • 你应该添加你自己的答案。

标签: model-view-controller asp.net-mvc-3 routing


【解决方案1】:

除了您应该使用ActionResult 而不是ViewResult 作为返回类型之外,您的代码没有任何问题,因为当您重定向时没有呈现视图。 RedirectToRoute 方法返回 RedirectToRouteResult,因此您的代码将无法编译。这就是为什么让所有控制器操作方法签名返回作为基类的 ActionResult 始终是最佳实践的原因:

public ActionResult Index()
{
     return View();
}

public ActionResult Category(string categoryName)
{
    var category = (db.Categories.Where(i => i.Name == categoryName).FirstOrDefault()) ?? null;
    if (category != null)
    {
        return View(category);
    }

    return RedirectToRoute("Choose_your_dvd_Index");
}

假设您的路线看起来与您在问题中显示的完全一样,如果用户请求例如 /choose-your-dvd/foobar 并且在您的数据库中找不到 foobar 类别,他将正确地重定向到相同的 Index 操作控制器。

【讨论】:

  • 谢谢达林:在我发帖后发现了一个:为了帮助别人,上面的代码有点错误,因为var category是一个bool,而不是一个category!!
猜你喜欢
  • 2011-08-22
  • 1970-01-01
  • 2023-03-14
  • 2011-10-16
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多