我正在使用MVC 4和EntityFramework 5.
在这个例子中,我尝试使用简单的表单参数保存新的“Contact”对象后,我得到了两个EntityValidationErros。
其中一个Contact属性是“Address”,它被填充在同一个视图中(与其他Contact的属性相同。
当我提交表单时,我得到一个全新的Contact对象,其中包含与表单参数匹配的完整Address atribute。 然而,当我尝试保存它时,我的联系人地址中缺少参数的EntityValidationError(确切地说是2)。
我的观点:
<div class="editor-label">
@Html.LabelFor(model => model.Address.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.City)
@Html.ValidationMessageFor(model => model.Address.City)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address.Street)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.Street)
@Html.ValidationMessageFor(model => model.Address.Street)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address.State_province)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.State_province)
@Html.ValidationMessageFor(model => model.Address.State_province)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address.Zip_postalCode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.Zip_postalCode)
@Html.ValidationMessageFor(model => model.Address.Zip_postalCode)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address.Country)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.Country)
@Html.ValidationMessageFor(model => model.Address.Country)
</div>
<br />
<p>
<input type="submit" value="Save" />
</p>
在ContactCOntroller中创建操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Contact contact)
{
try
{
if (ModelState.IsValid)
{
TempData["contact"] = contact;
unitOfWork.currentClient.Contacts.Add(contact);
unitOfWork.Save();
return View("Index");
}
return View(contact);
}
catch (Exception ex)
{
return View(contact);
}
}
任何想法?
答案 0 :(得分:1)
从模型状态中获取错误。
使用Linq:
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
另一种选择:
public static List<string> GetErrorListFromModelState
(ModelStateDictionary modelState)
{
var query = from state in modelState.Values
from error in state.Errors
select error.ErrorMessage;
var errorList = query.ToList();
return errorList;
}
资源: