我试图通过对我的视图模型使用OOP来实现DRY原则:
public class ItemBase
{
[Display(Name = "Description - Displayed in the list (so make this meaningful)")]
[Required]
public string Description { get; set; }
[Display(Name = "Username")]
[Required]
public string UserName { get; set; }
[Display(Name = "Optional Secondary Credential")]
public string SecondCredential { get; set; }
[Display(Name = "Location - Ideally a URL")]
[Required]
public string Location { get; set; }
[Display(Name = "Additional Notes")]
public string Notes { get; set; }
}
public class ItemDisplay : ItemBase
{
[Required]
public Int32 ItemId { get; set; }
public ApplicationUser Creator { get; set; }
}
public class ItemEdit : ItemBase
{
[Required]
public Int32 ItemId { get; set; }
}
public class ItemAdd : Itemase
{
[Required]
public Int32 Parent_CategoryId { get; set; }
}
这确实很有用......但是,当我想使用ItemDisplay类在视图中显示数据时,它会显示Display属性数据。如果不将所有成员放入ItemDisplay类而没有Display attrbute,我将如何让视图忽略这些?
查看代码
<article class="first">
<h2>Details</h2>
<div class="form-horizontal toppaddding">
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.Description)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.UserName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.SecondCredential, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.SecondCredential)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.Password)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.Location, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.Location)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ViewItem.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Raw(Model.ViewItem.Notes)
</div>
</div>
</div>
</article>
答案 0 :(得分:0)
Html.LabelFor
助手首先查找Display dataAnnotation,如果没有,则默认输出类中属性的名称。
如果您不想在此特定视图中使用“显示数据”注释,请不要使用Html.LabelFor
帮助程序,而是创建自己的标签标记,或者只输出您想要的任何内容。在包含模型数据的<div>
之前说。
<div class="form-group">
<label class = "control-label col-md-2">Alternate Description Label Text</label>
<div class="col-md-10">
@Html.Raw(Model.ViewItem.Description)
</div>
</div>
在这种情况下,您不是在创建输入表单,因此您可以考虑使用span而不是标签。
答案 1 :(得分:0)
您可以使用接受labelText
参数
LabelFor
重载
@Html.LabelFor(model => model.ViewItem.UserName,
Model.ViewItem.Description,
htmlAttributes: new { @class = "control-label col-md-2" })