我正在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>
现在我要完成的是网址将是:
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 = ""}
);
但它不断抛出错误:
参数字典包含不可为空类型"System.Int32"的参数"id"的空条目,用于"MyBlog.Controllers.BlogController"中的方法"System.Web.Mvc.ActionResult Details(System.String, Int32("。可选参数必须是引用类型、可为 null 的类型或声明为可选参数。
我想我无法抓住这个"路由"的东西......我怎样才能完成这项任务?
如果您只是不希望id
出现在 URL 中,但确实想将其发送到操作中,那么最简单的方法是使用表单或 ajax POST
它。
@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 }
);
那么,您的任何一条路由都应该没问题,尽管如果您不打算从 URL 中提取它,则在其中任何一条路由中提及id
都没有意义。
诚然,在适合GET
的场景中使用POST
很奇怪,但在GET
中,您只能通过 URL 发送信息,即路由值和查询字符串。 使用 POST
允许您在表单集合中发送它,这在 URL 中显然看不到,但 MVC 将检查其模型绑定的值,这允许您仍然获取id
作为操作方法参数。