简体   繁体   English

将ModelState传递给RedirectToAction到ViewModel中

[英]Passing ModelState to RedirectToAction into a ViewModel

How can I pass back the validation errors I find when using DbEntityValidationException 当使用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 });
            }

It appears that when I do this RedirectToAction my ModelState refreshes and I can not view the errors it found. 看来当我执行RedirectToAction我的ModelState刷新了,并且我无法查看它发现的错误。

The AccessDetail populates a view model that has many different sources of data in it. AccessDetail填充其中包含许多不同数据源的视图模型。 So passing just the access to the View does not work. 因此,仅将对视图的访问权限传递不起作用。

I was looking at this question but it didn't fit my needs as my view is populated with a ViewModel 我当时在看这个问题,但由于我的视图是用ViewModel填充的,所以它不符合我的需求

RedirectToAction helper method issues a 302 response to the client which makes the clients to issue a new GET request to the new url. RedirectToAction帮助程序方法向客户端发出302响应,使客户端向新的url发出新的GET请求。

If you want to persist some data between these 2 requests, Use TempData . 如果要在这两个请求之间保留一些数据,请使用TempData

TempData["Errors"] = yourListOfErrors;
return RedirectToAction("AccessDetail", "Home", new { IDValue = access.ID });

And in your GET action, read the TempData values and display it. 然后在GET操作中,读取TempData值并显示它。

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. 但是,如果您不想执行RedirecToAction,则可以简单地将viewmodel返回到视图,并且如果您具有ValidationSummary帮助器方法,它将显示验证错误消息。

simply use 只需使用

return View(model);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM