Html.BeginForm 和 HTML 属性不指定控制器和操作

发布于 2024-08-12 08:44:58 字数 302 浏览 2 评论 0原文

我喜欢它的简洁性

using (Html.BeginForm())

,但讨厌添加 HTML 属性需要指定控制器、操作和表单方法。

using (Html.BeginForm("Action", "Controller", FormMethod.Post,
  new { id = "inactivate-form" })

有没有办法使用 Html.BeginForm 并为表单指定 HTML 属性,而无需手动连接其他所有内容?

I like the cleanliness of

using (Html.BeginForm())

And hate that adding HTML attributes requires specifying the controller, action, and form method.

using (Html.BeginForm("Action", "Controller", FormMethod.Post,
  new { id = "inactivate-form" })

Is there a way to use Html.BeginForm and specify HTML attributes for the form without manually wiring everything else up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

肤浅与狂妄 2024-08-19 08:44:58

为什么不直接使用纯 html 呢?

<form id="inactivate-form" method="post" >
</form>

Why would you not just use plain html?

<form id="inactivate-form" method="post" >
</form>
夏雨凉 2024-08-19 08:44:58

您可以创建一个自定义扩展,添加“Id-ed”表单:

public static MvcForm BeginIdedForm(this HtmlHelper htmlHelper, string id)
{
    return htmlHelper.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "id", id } });
}

然后用法就变成了

using(Html.BeginIdedForm("inactiveate-form")) 

You could create a custom extension that adds an 'Id-ed' form:

public static MvcForm BeginIdedForm(this HtmlHelper htmlHelper, string id)
{
    return htmlHelper.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "id", id } });
}

Usage then just becomes

using(Html.BeginIdedForm("inactiveate-form")) 
鸩远一方 2024-08-19 08:44:58

类似于 @nick-olsen 的回答,使用 null 作为操作/控制器参数:

@Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() {{ "id", id }}

BeginForm 方法最终调用 System.Web.Mvc.RouteValuesHelpers.MergeRouteValues ,它会从 RequestContext.RouteData 中查找操作和控制器名称(如果它们是 < code>null 回发到创建表单的同一操作/控制器。

Similar to @nick-olsen's answer use null for the action/controller parameters:

@Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() {{ "id", id }}

The BeginForm method eventually calls System.Web.Mvc.RouteValuesHelpers.MergeRouteValues which looks up the action and controller names from the RequestContext.RouteData if they're null posting back to the same action/controller as the form was created from.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文