怎么删除?和=来自MVC网址

时间:2013-05-03 18:43:17

标签: c# asp.net-mvc-3 asp.net-mvc-routing asp.net-routing

这是我的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 

我该怎么做才能实现这个目标?

1 个答案:

答案 0 :(得分:1)

将路线定义更改为不将Post作为参数。

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

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

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

的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 })