2011-06-13 126 views
0

我是新来的MVC,很抱歉,如果这是一个有点小白的问题:MVC 3路由问题

我设立在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" } 
    ); 

具体来说,我映射“选择 - 你-DVD/{类别名称}”我的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() ; 
} 

我想将用户重定向到只是“选择 - 你-DVD”如果他们进入一个无效的类别名称? (即浏览器中的URL改变)

谢谢!

+0

好的,我已经完成了! 更改为一个ActionResult,它工作! (失去了第二个“返回查看()”)! – mp3duck 2011-06-13 16:43:03

+0

你应该添加你自己的答案。 – 2011-06-13 16:44:52

回答

0

你的代码没有什么问题,除了你应该使用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操作。

+0

感谢Darin:发现刚刚发布的一个: 为了帮助其他人,上面的代码有点不对,因为var类是一个bool,而不是一个类! – mp3duck 2011-06-14 06:54:43