如何将两个参数从视图传递到控制器,但在 url 中只显示一个



我正在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作为操作方法参数。

相关内容

最新更新