<%= Html.EditorFor(product => product.Name) %>
我需要生成的输出设置autocomplete =“off”属性。
我缺少什么?
编辑:
我正在寻找一个接受EditorFor的扩展方法来接受属性的键/值字典,所以我可以像这样调用它:<%= Html.EditorFor(product => product.Name, new { autocomplete = "off" } ) %>
这里是为LabelFor完成的,但需要针对EditorFor
进行调整 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) {
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.SetInnerText(labelText);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
EDIT2: 我意识到它不能被命名为EditorFor,因为已经存在一个被覆盖的EditorFor,它接受一个匿名类型,请参见http://msdn.microsoft.com/en-us/library/ff406462.aspx ..无论如何,我们可以用不同的名称命名,没有大人物。
答案 0 :(得分:4)
您需要使用自定义模板生成带有属性的input元素,或者您可以向页面添加一些javascript以添加客户端属性。
<%= Html.EditorFor( product => product.Name, "NoAutocompleteTextBox" ) %>
然后在Shared / EditorTemplates中你需要一个定义的NoAutocompleteTextBox.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { autocomplete = "off" }) %>
或jQuery方式,在所有文本输入上设置它
$(function() {
$('input[type=text]').attr('autocomplete','off');
});
答案 1 :(得分:2)
public static MvcHtmlString EditorForAttr<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) {
return EditorForAttr(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString EditorForAttr<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes) {
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
TagBuilder tag = new TagBuilder("input");
tag.GenerateId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.MergeAttribute("name", htmlFieldName);
tag.MergeAttribute("type", "text");
tag.MergeAttribute("value", metadata.Model == null ? "" : metadata.Model.ToString()); // Not sure if this is correct.
tag.MergeAttributes(htmlAttributes, true);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.SelfClosing));
}