在MVC4应用程序中,我有一些继承为视图模型的Business Objects。我想在视图模型中使用DataAnnotations
,而不是在Business Object中指定它。这可能。
Business Objects
public class Country
{
[Display(Name = "Country")]
public virtual int CountryId { get; set; }
public virtual string CountryName { get; set; }
public virtual string CountryCode { get; set; }
}
public class State : Country
{
[Display(Name = "State")]
public virtual int StateId { get; set; }
public virtual string StateName { get; set; }
public virtual string StateCode { get; set; }
}
public class City : State
{
public virtual int CityId { get; set; }
[Display(Name = "City")]
public virtual string CityName { get; set; }
}
查看模型
public class Regional
{
public Regional()
{
Countries = new Collection<Country>();
States = new Collection<State>();
City = new City();
}
public Collection<Country> Countries { get; set; }
public Collection<State> States { get; set; }
[Required(ErrorMessage = "Required")]
public City City { get; set; }
}
在上面的代码中,我正在使用City Property的数据注释。
有什么想法吗?
我的观点
@using (Html.BeginForm(Actions.AddCity, Controllers.AdminUtility, FormMethod.Post))
{
<div class="alert-error">
@Html.ValidationSummary()
</div>
<div class="row-fluid">
<fieldset class="form-horizontal">
<legend class="header">Add City</legend>
<div class="control-group">
@Html.LabelFor(m => m.City.CountryId, new { @class = "control-label" })
<div class="controls">
@Html.DropDownListFor(m => m.City.CountryId, new SelectList(Model.Countries, "CountryId", "CountryName"),"", new { @class = "chosen", data_placeholder = "Choose Country..." })
</div>
</div>
<div class="control-group">
@Html.LabelFor(m => m.City.StateId, new { @class = "control-label" })
<div class="controls">
@Html.DropDownListFor(m => m.City.StateId,new SelectList(Model.States, "StateId","StateName"), "",new { @class = "chosen", data_placeholder = "Choose State..." })
</div>
</div>
<div class="control-group">
@Html.LabelFor(m => m.City.CityName, new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(m => m.City.CityName)
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" />
</div>
</div>
</fieldset>
</div>
}
答案 0 :(得分:1)
您的验证是说该课程是必需的。您希望CityName是必需的,因此在您的方案中,不需要,您必须在域模型上指定属性。
只是一个注释 - 我认为您的域模型不是很清楚。城市,州和国家不相互继承,它们只是相关的。一个国家位于一个国家,它不是一个国家......此外,您应该始终验证您的域对象,因为它们可能来自多个来源。然后,您的ViewModel将具有特定于该视图的其他验证 - 可能还有一些用于ui处理的附加数据,不需要传递到您的域等等。