我正在编写一个代码第一个MVC 5应用程序,为了简洁起见,我可以说我有两个这样定义的模型:
public class Platform { [Key] public int Id { get; set; } [required(ErrorMessage = "You must select a manufacturer")] [DisplayName("Manufacturer")] public int ManufacturerId { get; set; } public virtual Manufacturer Manufacturer { get; set; } [required(ErrorMessage="You must enter a name for the platform")] [StringLength(50,ErrorMessage="Reduce length to 50 characters or less")] public string Name { get; set; } }
和
public class Manufacturer { [Key] public int Id { get; set; } [required(ErrorMessage="You must enter a name for the manufacturer")] [StringLength(50,ErrorMessage="Reduce length to 50 characters or less")] public string Name { get; set; } public virtual ICollection<Platform> Platforms { get; set; } }
在创建带视图的MVC 5控制器时,使用Entity Framework对这些模型的脚手架,所有CRUD操作都能正常工作.另一方面,表单元素是未格式化的,缺少Bootstrap想要的表单控件类.
我可以通过在其中添加一个类似@ Html.TextBox(“”,ViewData.TemplateInfo.FormattedModelValue,new {@class =“form-control”})之类的EditorTemplate来解决这个问题,但肯定是一个Bootstrap的脚手架MVC 5项目应该已经发出有效代码吗?看看各种MVC 5教程,他们似乎正确地使用了正确的样式,所以我对我做错了什么感到困惑.
作为参考,每个模型的Create.cshtml文件中的输出(为简洁而剪切到重要的表单元素)是:
<div class="form-group"> @Html.LabelFor(model => model.ManufacturerId,"ManufacturerId",new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("ManufacturerId",String.Empty) @Html.ValidationMessageFor(model => model.ManufacturerId) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Name,new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> </div>
和
<div class="form-group"> @Html.LabelFor(model => model.Name,new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> </div>
为什么在模型中设置DisplayName时,将ManufacturerId指定为下拉列表的标签文本?
为什么使用DropDownList()而不是强类型的DropDownListFor()下拉?
先感谢您.
解决方法
GitHub.
我也得到了微软的Rick Anderson的回复,他在www.asp.net上写了几个教程,他证实了这一点……
Great catch. Actually,some of the images in my tutorial are from Beta and RC that are using bootstrap v2,not V3,so our images will differ. Look at the views for your account controller to see “form-control”. You can download my complete project and compare with your project.
关于你的另一个问题,我遇到了同样的问题,并认为这可能是一个错误.某些注释似乎被忽略了.尝试将[ForeignKey()]注释添加到Platform.ManufacturerId并查看它是否影响字段标签.