1

嗨,这是我的 ActionLink

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

这也是发布操作结果

 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 

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

4

1 回答 1

1

将您的 Route 定义更改为没有 Post 参数。

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

并确保您的路线高于 MVC 的默认路线。

更新:使用我使用的确切示例进行更新

全球.asax

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

~/Views/Blog/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 })
于 2013-05-03T18:53:00.893 回答