问题描述
如何传回使用 DbEntityValidationException
try
{
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
this.ModelState.AddModelError(validationError.PropertyName,
validationError.ErrorMessage);
}
}
return RedirectToAction("AccessDetail", "Home", new { IDValue = access.ID });
}
看来,当我这样做时 RedirectToAction
我的 ModelState
刷新,我无法查看发现的错误。
It appears that when I do this RedirectToAction
my ModelState
refreshes and I can not view the errors it found.
AccessDetail填充了一个视图模型,其中包含许多不同的数据源。因此,仅将访问权限传递给视图是行不通的。
The AccessDetail populates a view model that has many different sources of data in it. So passing just the access to the View does not work.
我正在查看此,但由于我的视图中装有ViewModel,因此它不符合我的需求
I was looking at this question but it didn't fit my needs as my view is populated with a ViewModel
推荐答案
RedirectToAction
辅助方法对 302
响应发出客户端,使客户端可以向新的url发出新的 GET 请求。
RedirectToAction
helper method issues a 302
response to the client which makes the clients to issue a new GET request to the new url.
如果您想在这两个请求之间保留一些数据,使用 TempData
。
If you want to persist some data between these 2 requests, Use TempData
.
TempData["Errors"] = yourListOfErrors;
return RedirectToAction("AccessDetail", "Home", new { IDValue = access.ID });
在您的 GET
操作中,阅读
但是如果您不想执行RedirecToAction,则可以简单地将viewmodel返回到视图,并且您具有ValidationSummary帮助器方法。 ,它将显示验证错误消息。
But If you do not want to do the RedirecToAction, You may simply return the viewmodel back to the view and if you have the ValidationSummary helper method, it will show the validation error messages.
简单使用
return View(model);
这篇关于将ModelState传递给RedirectToAction到ViewModel中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!