Jon*_*ood 4 asp.net-mvc razor asp.net-mvc-3
我需要一个ASP.NET MVC Razor页面上的表单.我的偏好是使用以下语法:
@using (Html.BeginForm())
{
}
Run Code Online (Sandbox Code Playgroud)
但是,我需要在表单中添加几个属性.所以我最终得到了以下内容:
@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "value" }))
{
}
Run Code Online (Sandbox Code Playgroud)
然而,这具有不希望的副作用.如果此页面的请求中有查询参数,则第一个表单会在提交表单时传递它们.但是,第二个版本没有.
我真的不知道为什么BeginForm()不支持属性,但是BeginForm()当提交for时,有没有直接的方法来添加属性并仍然传递任何查询参数?
编辑:
在研究之后,似乎最好的解决方案是这样的:
<form action="@Request.RawUrl" method="post" name="value">
</form>
Run Code Online (Sandbox Code Playgroud)
但是,使用此语法时,将禁用客户端验证.在没有更复杂和可能不可靠的结构的情况下,似乎没有很好的解决方案.
确实如此,但我会使用自定义帮助程序来保留用于客户端验证的表单上下文:
public static class FormExtensions
{
private static object _lastFormNumKey = new object();
public static IDisposable BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
{
string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
return htmlHelper.FormHelper(rawUrl, FormMethod.Post, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
private static int IncrementFormCount(IDictionary items)
{
object obj2 = items[_lastFormNumKey];
int num = (obj2 != null) ? (((int)obj2) + 1) : 0;
items[_lastFormNumKey] = num;
return num;
}
private static string DefaultFormIdGenerator(this HtmlHelper htmlhelper)
{
int num = IncrementFormCount(htmlhelper.ViewContext.HttpContext.Items);
return string.Format(CultureInfo.InvariantCulture, "form{0}", new object[] { num });
}
private static IDisposable FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
var builder = new TagBuilder("form");
builder.MergeAttributes<string, object>(htmlAttributes);
builder.MergeAttribute("action", formAction);
builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
bool flag = htmlHelper.ViewContext.ClientValidationEnabled && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;
if (flag)
{
builder.GenerateId(htmlHelper.DefaultFormIdGenerator());
}
htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
var form = new MvcForm(htmlHelper.ViewContext);
if (flag)
{
htmlHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];
}
return form;
}
}
Run Code Online (Sandbox Code Playgroud)
可以像这样使用:
@using (Html.BeginForm(htmlAttributes: new { name = "value" }))
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4958 次 |
| 最近记录: |