带有 PartialViews 的无效 ModelState
我有以下操作,
[GET("Foo")]
public virtual ActionResult Foo()
{
return View(new FooViewModel());
}
此操作的视图
@{ Html.RenderAction(MVC.FooBar.AddFoo()); }
使用控制器操作
[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
var viewModel = new AddFooViewModel();
return PartialView(viewModel);
}
[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
// If ModelState is invalid, how do I redirect back to /Foo
// with the AddFooViewModel ModelState intact??
if (!ModelState.IsValid)
return MVC.FooBar.Foo();
// ... persist changes and redirect
return RedirectToAction(MVC.FooBar.Foo());
}
调用此部分视图如果有人提交带有 ModelState 错误的 AddFoo 表单,我希望 POST 操作重定向回 /Foo 并显示带有 ModelState 错误的 AddFoo 部分视图。处理这个问题的最佳方法是什么?
I have the following action
[GET("Foo")]
public virtual ActionResult Foo()
{
return View(new FooViewModel());
}
the view for this action calls this partial view
@{ Html.RenderAction(MVC.FooBar.AddFoo()); }
with controller actions
[ChildActionOnly]
[GET("Foo/Add")]
public virtual ActionResult AddFoo()
{
var viewModel = new AddFooViewModel();
return PartialView(viewModel);
}
[POST("Foo/Add")]
public virtual ActionResult AddFooPost(AddFooViewModel viewModel)
{
// If ModelState is invalid, how do I redirect back to /Foo
// with the AddFooViewModel ModelState intact??
if (!ModelState.IsValid)
return MVC.FooBar.Foo();
// ... persist changes and redirect
return RedirectToAction(MVC.FooBar.Foo());
}
If somebody submits the AddFoo form with ModelState errors, I want the POST action to redirect back to /Foo and show the AddFoo partial view with the ModelState errors. What's the best approach to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可以通过两种方式实现这一目标:
我更喜欢第二个选项。
I think you could achieve that in 2 ways:
I prefer the second option.
我最终将视图模型放入
TempData
中,如下所示,并使用控制器上的ModelStateToTempData
属性I ended up putting the viewmodel into
TempData
like this with theModelStateToTempData
attribute on the controller