Custome MVC Url Rout to display mixture of Id and UrlSlug

二次信任 提交于 2019-12-02 08:52:11

Have you tried setting both your postId and slug to be UrlParameter.Optional? routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}", new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=UrlParameter.Optional});

EDIT

I got this to work locally. What I've got is a model:

public class HomeViewModel
{
    public Guid PostID { get; set; }
    public string Slug { get; set; }
}

A Controller with two actions:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        Guid guid = Guid.NewGuid();

        var model = new HomeViewModel { PostID = guid, Slug = "this-is-a-test" };
        return View(model);
    }

    public ActionResult Post(Guid postID, string slug)
    {
        // get the post based on postID
    }
}

And a View with an actionlink:

@model MvcApplication1.Models.HomeViewModel
@{
    ViewBag.Title = "Home Page";
}
@Html.ActionLink("Click me!", "Post", new { postId = Model.PostID, slug = Model.Slug})

To get the routing to work I had to hard-code the route as it comes before the Default route:

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

    routes.MapRoute("IdSlugRoute", "Home/Post/{postID}/{slug}",
                        new { controller = "Home", action = "Post", postID = Guid.Empty, slug = UrlParameter.Optional });

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

}

Make sure your custom route is ABOVE the default one. It will stop at the first matching route it finds.

change your route to use postId rather than Id

routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
                            new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=""});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!