在 MVC4 应用程序中,我有一些作为视图模型继承的业务对象。我想DataAnnotations
在视图模型中使用而不是在业务对象中指定它。那可能吗。
业务对象
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>
}