获取错误消息,如果ModelState.IsValid失败了呢? [英] Get error message if ModelState.IsValid fails?
问题描述
我有这个功能在我的控制器。
I have this function in my controller.
[HttpPost]
public ActionResult Edit(EmployeesViewModel viewModel)
{
Employee employee = GetEmployee(viewModel.EmployeeId);
TryUpdateModel(employee);
if (ModelState.IsValid)
{
SaveEmployee(employee);
TempData["message"] = "Employee has been saved.";
return RedirectToAction("Details", new { id = employee.EmployeeID });
}
return View(viewModel); // validation error, so redisplay same view
}
它不断失败, ModelState.IsValid
保持返回false并重新显示视图。但我不知道是什么错误。
It keeps failing, ModelState.IsValid
keeps returning false and redisplaying the view. But I have no idea what the error is.
有没有办法让错误并重新显示它给用户?
Is there a way to get the error and redisplay it to the user?
推荐答案
您可以通过使用做到这一点,而无须在你的行动做什么特别的你的看法<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationsummary.aspx\">Html.ValidationSummary()显示所有的错误信息,或<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationmessagefor%28v=vs.98%29.aspx\">Html.ValidationMessageFor()以示对模型的特定属性的消息。
You can do this in your view without doing anything special in your action by using Html.ValidationSummary() to show all error messages, or Html.ValidationMessageFor() to show a message for a specific property of the model.
如果你仍然需要从你的行动或控制器中出现的错误,请参阅<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstate.errors.aspx\">ModelState.Errors财产
If you still need to see the errors from within your action or controller, see the ModelState.Errors property
这篇关于获取错误消息,如果ModelState.IsValid失败了呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!