2

我正在 MVC 4 中构建一个应用程序,但我被困在一件事上。

我有一个控制器和动作:

public ActionResult Details(string pattern, int id)
{
    Post post = repository.GetPostById(id);

    return View(post);
}

在视图中:

<div class="innerbody">
    @Model.Description @Html.ActionLink("Czytaj dalej...", "Details", new { id = Model.PostId, pattern = Model.ShortUrl})
</div>

现在我想要完成的是 url 将是:

www.mysite.com/blog/pattern

没有id. “模式”是ShortUrl从帖子标题中提取的。

我尝试将这些不同的路由添加到 RouteConfig:

routes.MapRoute(
    name: "Details",
    url: "{Controller}/{pattern}",
    defaults: new {controller = "Blog", action = "Details", pattern = "", id = UrlParameter.Optional}
); 

或者

routes.MapRoute(
    name: "Details",
    url: "{Controller}/{pattern}",
    defaults: new {controller = "Blog", action = "Details", pattern = ""}
);

但它不断抛出错误:

参数字典包含“MyBlog.Controllers.BlogController”中方法“System.Web.Mvc.ActionResult Details(System.String, Int32)”的不可空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。

我想我无法捕捉到这个“路由”的东西......我怎么能完成这个任务?

4

1 回答 1

1

如果您只是不希望id出现在 URL 中,但确实想将其发送到操作,那么最简单的方法就是POST使用表单或 ajax。

@using (Html.BeginForm("Details", "Blog", new { pattern = Model.ShortUrl }))
{
    @Html.HiddenFor(m => m.PostId)
}

或者

$.post(
    @Url.Action("Details", "Blog", new { pattern = Model.ShortUrl }),
    new { id: Model.PostId }
);

那么,您的任何一条路线都应该没问题,但id如果您不打算从 URL 中提取它,那么在其中任何一条中都没有必要提及。

诚然,将 aPOST用于适合 a 的场景很奇怪,GET但在 a 中,GET您只能通过 URL 发送信息,即路由值和查询字符串。使用 aPOST允许您将其发送到在 URL 中显然看不到的表单集合中,但 MVC 将检查其值以进行模型绑定,这使您仍然可以获取id作为操作方法的参数。

于 2013-08-30T20:24:27.293 回答