我有两个实体:可选属性中MVC必选属性
public class ParentThing
{
[Key]
public int Id { get; set; }
[Required]
public ChildThing TheFirstThing { get; set; }
public ChildThing TheSecondThing { get; set; }
}
public class ChildThing
{
[Key]
public int Id { get; set; }
[Required]
public string Code { get; set; }
public string Name { get; set; }
}
和视图模型:
public class ParentViewModel
{
public string Message { get; set; }
public ParentThing ParentThing { get; set; }
}
和视图:
@using (@Html.BeginForm())
{
<label>Code 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Code)
<label>Name 1</label>
@Html.EditorFor(model => model.ParentThing.TheFirstThing.Name)
<label>Code 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Code)
<label>Name 2</label>
@Html.EditorFor(model => model.ParentThing.TheSecondThing.Name)
<input type="submit" value="Save" />
}
在我的帖子后,我添加将ParentThing添加到上下文并尝试保存更改。根据需要,我会在ParentThing的TheSecondThing属性的Code属性上收到验证错误。
保存包含所需属性的可选属性有哪些替代方法?
另一种方法是删除视图模型中对实体类的依赖关系。你想使用数据传输对象(DTO)。这个http://stackoverflow.com/questions/5995140/models-viewmodels-dtos-in-mvc-3-application将帮助你开始。 – Jasen