开发者

ASP.NET MVC 3.0 Routes and Passing Parameters

I am trying to pass parameters to the route but I am having a hard time. I want that when I type "Articles/230" in the URL it should invoke the Detail action as shown below:

 public ActionResult Detail(int id)
       {
           return View();
       }

I have the following in my Global.asax file:

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{开发者_如何学编程action}/{id}", // URL with parameters
                new { controller = "Articles", action = "Index", id = UrlParameter.Optional } // Parameter defaults


            );

            routes.MapRoute(
               "ArticleDetails", // Route name
               "Articles/{id}", // URL with parameters
               new { controller = "Articles", action="Detail", id = 0 } // Parameter defaults

           );

        }

And here is the view:

@foreach(var article in Model) 
{
    <div class="article_title">
   @Html.ActionLink(@article.Title, "Detail", "Articles", new { id = @article.Id})
    </div>
    <div>
    @article.Abstract
    </div>


The order of routes is important because they are evaluated in the same order they are defined. So oimply invert the order:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "ArticleDetails",
        "Articles/{id}",
        new { controller = "Articles", action = "Detail", id = 0 }
    );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Articles", action = "Index", id = UrlParameter.Optional }
    );
}

Now when you request Articles/123 it will invoke the Detail action on the Articles controller and pass 123 as the id parameter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜