ASP.NET MVC 3 - 数据Annoation和文本框渲染的最大长度/大小
我知道关于Razor视图文件,我们可以这样做: @ Html.TextBox(“username”,null,new {maxlength = 20 ,autocomplete =“off”})ASP.NET MVC 3 - 数据Annoation和文本框渲染的最大长度/大小
但是,我希望为MVC创建一个模型,该模型可以用来创建一个明确定义文本框大小和最大长度的窗体。我尝试在模型属性的顶部使用[StringLength(n)],但似乎只做了验证,而不是设置文本框的大小。
有没有办法,我们可以定义文本字段的长度作为模型属性顶部的数据注释?因此,最终,我们可以通过使用剃刀映射到模型来创建整个表单,而不是明确地逐个拾取模型属性以设置文本框的大小。
下面是一个使用StringLengthAttribute
自定义帮助的轮廓。
public class MyModel
{
[StringLength(50)]
public string Name{get; set;}
}
public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
var attributes = new Dictionary<string, Object>();
var memberAccessExpression = (MemberExpression)expression.Body;
var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);
if (stringLengthAttribs.Length > 0)
{
var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;
if (length > 0)
{
attributes.Add("size", length);
attributes.Add("maxlength", length);
}
}
return helper.TextBoxFor(expression, attributes);
}
这不行吗?
public class ViewModel
{
[StringLength(20)]
public string UserName {get;set;}
}
在查看:
@Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})
或:
@Html.EditorFor(x => x.UserName)
您提到的语法是正确的,但我希望只需调用@ Html.EditorForModel()并让它呈现模型中的所有字段,而不是分别明确地呈现每个字段。除此之外,我还希望能够将文本字段的大小定义为数据注释标记的一部分。请注意有[StringLength(20)]似乎没有将文本字段的大小设置为20.我希望这个澄清更多一点..谢谢! – frostshoxx
@frostshoxx指定模型中的文本字段大小等表示逻辑违反了MVC的核心原则。除非你的意思是maxlength .. – redwards510
我发现我更喜欢我的观点只是调用Html.EditorFor(...)。这意味着编辑器和显示模板决定了我的视图中控件的命运,这样我的视图代码就被清理了很多 - 它只是对编辑器有html和通用请求。
以下链接给在得到这个工作的工作样本的编辑模板 https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
我用我的String.cshtml编辑模板类似(进去共享/ EditorTemplates) 。
@model object
@using System.ComponentModel.DataAnnotations
@{
ModelMetadata meta = ViewData.ModelMetadata;
Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
@if(typeof(string).IsAssignableFrom(tModel)) {
var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();
var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
{
int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];
htmlOptions.Add("maxlength", maxLength);
if (maxLength < 20)
{
htmlOptions.Add("size", maxLength);
}
}
htmlOptions.Add("class", "regular-field");
<text>
@Html.TextBoxFor(m => m, htmlOptions)
</text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
//Show a Drop down for an enum using:
//Enum.GetValues(tModel)
//This is beyond this article
}
//Do other things for other types...
然后我模式被注释,如:
[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }
而且我查看简单地调用:
<div class="editor-label">
@Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.something.someField)
@Html.ValidationMessageFor(model => model.something.someField)
</div>
您也可能会注意到,我的String.cshtml编辑模板也自动神奇地处理Enum的,但是现在已经开始脱离当前的话题,所以我没有那个c赋,我就在这里说,该字符串编辑器模板可以拉额外的重量,并有可能谷歌已经对https://www.google.com/search?q=string+editor+template+enum
标签用工具提示成才的是一个自定义HTML帮助,只是下降的描述到标签的标题,有关每个标签的鼠标悬停的更多信息。
如果您想在编辑器模板中执行此操作,我会推荐此方法。
这看起来不错!在Html.EditorForModel()中可以使用与上面提到的类似的东西吗? 谢谢你的帮助。 – frostshoxx
@frostshoxx您可以使用[UIHintAttribute](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.uihintattribute.aspx)并为每种数据类型制作自定义模板。我还没有尝试过。 – Eranga