如何去除?and = from MVC url

本文关键字:from MVC url and 何去 | 更新日期: 2023-09-27 18:11:58

嗨,这是我的ActionLink

 @foreach (var item in Model)
    {
        <div>
            <h3>
                @Html.ActionLink(item.Title, "Post", new { postId = item.Id, postSlug = item.UrlSlug })
            </h3>
        </div>
    }

还有Post action result

 public ActionResult Post(Guid postId, string postSlug)
        {
            var post = _blogRepository.GetPostById(postId);
            return View("Post", post);
        }

,最后我在global中定义了这个路由。Asax支持上述操作

 routes.MapRoute("PostSlugRoute", "Blog/{Post}/{postId}/{postSlug}",
                            new
                                {
                                    controller = "Blog",
                                    action = "Post",
                                    postId = "",
                                    postSlug = ""
                                });

我在Url中得到的是这个

http://localhost:1245/Blog/Post?postId=554c78f1-c712-4613-9971-2b5d7ca3e017&postSlug=another-goos-post

但是我不喜欢这个!我希望是这样的

http://localhost:1245/Blog/Post/554c78f1-c712-4613-9971-2b5d7ca3e017/another-goos-post 

我该怎么做才能做到这一点??

如何去除?and = from MVC url

修改路由定义,不让Post成为参数

routes.MapRoute("PostSlugRoute",
    "Blog/Post/{postId}/{postSlug}", // Removed the {} around Post
    new { controller = "Blog", action = "Post", postId = "", postSlug = "" }
);

并确保你的路由在MVC的默认路由之上。

UPDATE:更新与我使用的

的确切示例

global.asax

routes.MapRoute("PostSlugRoute",
    "Blog/Post/{postId}/{postSlug}", // Removed the {} around Post
    new { controller = "Blog", action = "Post", postId = "", postSlug = "" }
);

~/视图/博客/Post.cshtml

@{
    Guid id = Guid.Parse("554c78f1-c712-4613-9971-2b5d7ca3e017");
    string slug = "another-goos-post";
    string title = "Another Goos Post";
}
@Html.ActionLink(title, "Post", new { postId = id, postSlug = slug })