如何在mvc 4中自动将占位符属性添加到html输入类型编号?
这是一个非常具体的问题。 我设法通过使用名为EmailAddress.cshtml
的编辑器模板自动将占位符属性添加到html5电子邮件输入类型,保存在~/Views/Shared/EditorTemplates/
文件夹中。 请参阅以下代码:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })
它的工作原理是因为我在视图模型中使用了[DataType(DataType.EmailAddress)]
DataAnnotation。
什么不起作用是我使用int?
变量。
public class MiageQuotaRequestViewModel { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Nombre de place demandées", Prompt = "Nombre de place")] [Range(0, 50, ErrorMessage = "La demande doit être comprise entre 0 et 50 places")] public int? RequestedQuota { get; set; } }
@Html.EditorFor
翻译此输入如下:
问题是我无法显示Prompt
DataAnnotation(通常由placeholder
翻译)。 此外, DataType
枚举没有任何“数字”或“整数”值,可以允许我像使用EmailAddress DataType一样使用EditorTemplate。
基于Pat Burke评论,我可以使用UIHint数据属性与良好的编辑器模板相结合。
这是一个例子( Editor Template
):
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark, type = "number" })
( ViewModel
)
public class MiageQuotaRequestViewModel { [Required] [UIHint("Number")] [DataType(DataType.EmailAddress)] [Display(Name = "Nombre de place demandées", Prompt = "Nombre de place")] [Range(0, 50, ErrorMessage = "La demande doit être comprise entre 0 et 50 places")] public int? RequestedQuota { get; set; } }
最后的结果是: