我试图从各种类型的视图中抽象出我的视图模型。整个编译过程没有问题,但我在“反映”(正式称为拆箱)数据注释方面遇到问题。
我有一个界面:
public interface IPerson
{
string FirstName { get;set;}
string LastName {get;set;}
}
我有两个类实现了这样的接口:
public class Employee : IPerson
{
[Required]
[Display(Description = "Employee First Name", Name = "Employee First Name")]
public string FirstName {get;set;}
[Required]
[Display(Description = "Employee Last Name", Name = "Employee Last Name")]
public string LastName {get;set;}
public int NumberOfYearsWithCompany {get;set;}
}
public class Client : IPerson
{
[Required]
[Display(Description = "Your first Name", Name = "Your first Name")]
public string FirstName {get;set;}
[Display(Description = "Your last Name", Name = "Your last Name")]
public string LastName {get;set;}
[Display(Description = "Company Name", Name = "What company do you work for?")]
public string CompanyName {get;set;}
}
人员编辑视图:视图/人员/编辑如下:
@model IPerson
<div class="clear paddingbottomxxsm">
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="clear paddingbottomxxsm">
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
员工编辑视图:视图/员工/编辑:
@model Employee
Html.RenderAction("Edit", "Person", new { person = Model });
<div class="clear paddingbottomxxsm">
<div class="editor-label">
@Html.LabelFor(model => model.CompanyName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.CompanyName)
@Html.ValidationMessageFor(model => model.CompanyName)
</div>
</div>
PersonController 在哪里:
public ActionResult Edit(IPerson person)
{
return PartialView(person);
}
一切都编译并渲染得很好。但是,数据注释正在丢失。
因此,Employee/Edit 的结果如下:
名字 [文本字段]
姓氏 [文本字段]
你在什么公司工作?[textfield] 公司名称是必填字段
有没有为具体类拆箱这些数据注释?
边注
我尝试将 IPerson 显式转换为 Employee:
@model IPerson
@{
var employee = (Employee)Model;
}
<div class="clear paddingbottomxxsm">
<div class="editor-label">
@Html.LabelFor(model => employee.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => employee.FirstName)
@Html.ValidationMessageFor(model => employee.FirstName)
</div>
</div>
<div class="clear paddingbottomxxsm">
<div class="editor-label">
@Html.LabelFor(model => employee.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => employee.LastName)
@Html.ValidationMessageFor(model => employee.LastName)
</div>
</div>
这样做需要名字,但没有从标签中获取显示属性。
更新 经过多次讨论这是否是拆箱,我还没有找到从(更基本的)具体类中获取数据注释的简单解决方案。使用视图(或助手)中的反射来获取具体类的数据注释确实会破坏简单性的目标。
我们有几个视图基本相同,但必填字段和显示名称略有不同。如果我可以将视图模型传递给接口视图并且它会找出所需的字段并显示属性,那将非常方便。如果有人想出办法做到这一点,将不胜感激。