31

我的网址如下所示:

customer/login?ReturnUrl=home

在登录视图中,我使用了这种运行良好的代码模式。

@using(Html.BeginForm())
{
   ...
}

这神奇地生成以下html

<form action="customer/login?ReturnUrl=home" method="post">

但是现在,我需要data-id="something"在表单中添加一个属性(例如,)。我怎样才能做到这一点?如果我没有任何查询字符串,我知道我可以这样做:

@using(Html.BeginForm(action, controller, FormMethod.Post, 
                      new { data_id="something" }))

但不知道如何添加应该在 html 中的查询字符串:

<form action="customer/login?ReturnUrl=home" method="post" data-id="something">

我考虑过<form>直接使用,但不知道如何指定可变的查询字符串。而且我不知道如何使用Html.BeginForm. 任何提示将不胜感激。

解析度:

现在,我使用<form>了以下提示How to get current url value in View。结果视图看起来像

<form action="@Request.Url.PathAndQuery" data-id="something" method="POST">

但是最好有一个重载的方法BeginForm

4

7 回答 7

21

这是对我有用的方式

Html.BeginForm("Profile", "Partner", routeValues: new {id=Partner.partner_id},method:FormMethod.Post)

这几乎就像重载方法存在问题,但通过指定事物是什么,它似乎工作正常......

于 2012-12-20T01:03:19.653 回答
17

从查询字符串创建 RouteValueDictionary:

RouteValueDictionary queryStringDictionary = new RouteValueDictionary(Request.QueryString.AllKeys.ToDictionary(key => key, key => (object)Request.QueryString[key]));

然后你可以将它与 Html.BeginForm 一起使用:

Html.BeginForm(null, null, queryStringDictionary, FormMethod.Post, new Dictionary<string, object> { { "autocomplete", "off" } })
于 2012-08-02T19:04:43.383 回答
16

我想这并不能直接回答这个问题,但为什么不直接使用普通的旧表单标签呢?

 <form action='customer/login?ReturnUrl=@Request.QueryString["ReturnUrl"]' method="post" data-id="something">

或者,您可以创建一个自定义 HtmlHelperExtension 来呈现带有路径和查询字符串的表单。在此 HtmlHelperExtension 中,您可以遍历查询字符串值并填充 routeValueDictionary,然后将其传递给 Html.BeginForm 构造函数。

如果您不想要如此可扩展的东西,您可以使用 Html.BeginForm 的重载构造函数 @Html.BeginForm("login", "customer", new {ReturnUrl = @Request.QueryString["ReturnUrl"]},FormMethod.Post, new {data-id="something"});

于 2011-09-06T17:54:13.333 回答
3

使用Reflector看代码,

BeginForm() 将直接将 rawUrl 传递给最终表单。BeginForm 上的任何其他重载都将通过一个辅助实用程序,该实用程序将删除查询字符串。

于 2015-04-02T17:37:06.730 回答
0

这对我有用:

@using (Html.BeginForm("index", "Photos", routeValues: new { user = pUser, album = pAlbum, }, method: FormMethod.Get))

明确的路线值和方法是必需的......

于 2017-08-23T03:42:56.697 回答
0

以防您还想添加其他属性。使用下面的代码

@using (Html.BeginForm("actionName", "controllerName", routeValues: new { lang = "en" }, method:FormMethod.Post, htmlAttributes: new { @class= "my-form", enctype = "multipart/form-data" }))
于 2017-10-20T19:51:20.797 回答
-1

尝试@using(Html.BeginForm(null, null, FormMethod.Post, new { data_id="something" }))

它应该使用默认逻辑来构造 url,就像你使用BeginForm()

(虽然在这种情况下从未尝试过,但我相信它应该有效)

于 2011-09-06T17:23:21.750 回答