c# – 如何通过在模型类上使用Display(prompt)属性在支架视图中
我使用脚手架为我生成视图和控制器,我使用EF代码第一语法.
我知道T4模板负责在生成的HTML /视图代码中实现属性值,但我没有看到VS 2015社区版可以使用默认的脚手架模板为占位符文本做任何事情. 根据我对使用[Display(Prompt =“some placeholder text”)]属性装饰模型属性的理解,导致某些占位符文本显示为输入文本框的占位符 但令我沮丧的是,这不会发生. 还有其他属性吗?还是我需要做的其他事情?或者是因为我使用脚手架来生成视图?或者是默认的T4模板没有很好地完成它的工作? 我的模型类代码如下所示: public class Status { public int ID { get; set; } [Required(ErrorMessage ="Status Name is needed!")] [Display(Name ="Status Name",Prompt ="Type something here!")] public string StatusName { get; set; } [Required] public string Description { get; set; } } 下面是生成的视图代码: @model LunchFeedback.Models.Status @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Status</h4> <hr /> @Html.ValidationSummary(true,"",new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.StatusName,htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.StatusName,new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.StatusName,new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description,htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Description,new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description,new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List","Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 编辑: 我很清楚,直接编辑视图文件并添加占位符持有者可以完成这项工作. @Html.EditorFor(model => model.StatusName,new { htmlAttributes = new { @class = "form-control",placeholder = "Type something here!" } }) 但我想控制模型中的所有东西,并希望使用脚手架.最好甚至编辑/定制T4模板来这样做. 解决方法
DisplayAttribute的Prompt属性将值添加到与属性关联的ModelMetadata的WaterMark属性.它不用于生成html占位符属性.
您希望将其值用作占位符属性,但另一个开发人员可能希望使用它来生成工具提示(使用title属性),因此可以让开发人员知道如何使用它. 脚手架编辑视图的T4模板为模型的属性生成@Html.Editor(),这样您就可以在/ Views / Shared / EditorTemplates文件夹中创建自己的EditorTemplates(或/ Views / youControllerName / EditorTemplates,如果您想要更多特定的模板用于特定的控制器) 请注意,EditorFor()方法首先在/ Views / youControllerName / EditorTemplates中搜索模板.如果找不到,则在/ Views / Shared / EditorTemplates中搜索,如果找不到,则使用默认的EditorTemplate 例如,要为所有属性为字符串的属性使用模板,请在EditorTemplates文件夹中创建名为String.cshtml的局部视图 @Html.TextBox("",ViewData.ModelMetadata.Model,new { placeholder = ViewData.ModelMetadata.Watermark }) 或者仅限于将此模板用于某些属性,将部分(例如)PlaceHolder.cshtml命名为属性,然后在属性上使用UIHintAttribute [Display(Name ="Status Name",Prompt ="Type something here!")] [UIHint("PlaceHolder")] public string StatusName { get; set; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |