开发者

MVC 3 Routing question

I am new to MVC, so sorry if this is a bit of a noob question:

I am setting up some custom routes in 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" }
    );

Specifically, I am mapping "Choose-you-dvd/{categoryName}" to my DVD controller, where I have the following view result, as well as having the default "choose-your-dvd" page.

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() ;
}

I want to redirect the user to just "Choose-your-dvd" if they enter an invalid category name? (i.e. the URL in the browser changes)

Thanks开发者_C百科!


There is nothing wrong with your code other than the fact that you should use ActionResult as return type instead of ViewResult because when you redirect there is no view rendered. The RedirectToRoute method returns a RedirectToRouteResult so your code won't compile. That's why it's always best practice to have all your controller action method signatures return ActionResult which is the base class:

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");
}

Assuming your routes look exactly as you have shown in your question if a user requests for example /choose-your-dvd/foobar and the foobar category is not found in your database he will correctly be redirected to the Index action on the same controller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜