如何在ASP.NET MVC子操作处理程序返回模型状态 [英] How to return model state from child action handler in ASP.NET MVC

查看:236
本文介绍了如何在ASP.NET MVC子操作处理程序返回模型状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的博客引擎,我有一个显示博客内容一个控制器动作,并在该视图中,我称之为Html.RenderAction(...)来渲染CreateComment的形式。当用户发布的注释,后由评论控制器(不是博客控制器)来处理。

In my blog engine, I have one controller action that displays blog content, and in that view, I call Html.RenderAction(...) to render the "CreateComment" form. When a user posts a comment, the post is handled by the comment controller (not the blog controller).

如果注释数据是有效的,我只是返回一个重定向回博客页面的URL。

If the comment data is valid, I simply return a Redirect back to the blog page's URL.

如果注释数据是无效的(如评论身体是空的),我想与错误信息传回返回的ViewData到博客控制器,并通过博客欣赏到CreateComment动作/视图,以便我可以显示哪些字段坏的。

If the comment data is invalid (e.g. comment body is empty), I want to return the ViewData with the error information back to the blog controller and through the blog view to the CreateComment action/view so I can display which fields are bad.

我有在启用JavaScript本通过AJAX做工精细,但现在我的工作在哪里的Javascript可能被禁用的情况下。

I have this working fine via AJAX when Javascript is enabled, but now I'm working on the case where Javascript might be disabled.

如果我从评论控制器返回RedirecToAction或重定向,模型的状态信息将丢失。

If I return a RedirecToAction or Redirect from the comment controller, the model state information is lost.

任何想法?

推荐答案

您可以存储您的ModelState或ViewData的(其​​中包含的ModelState)中的TempData你做重定向前,再后来把它拿来:

You could store your ModelState or ViewData (which contains ModelState) in TempData before you do the redirect, and then fetch it afterwards:

// In your CreateComment action before redirect
if (!ModelState.IsValid)
{
    TempData["ViewData"] = ViewData;
}

// In your Blog controller's action to which you redirected
if (null != TempData["ViewData"])
{
    ViewData = (ViewDataDictionary)TempData["ViewData"];
}

另外,你可以创建自己的RouteData,设置控制器和行动,清除反应,抓住this.Context并转储到一个新的RequestContext,使用使用您创建的路由数据ControllerBuilder类创建一个新的一个IController之前,然后重写你的路径,并使用了新的要求上下文中执行控制器。某处在那里你会在你的ModelState转储到结转。我还没有尝试过,这似乎矫枉过正。

Alternatively, you could create your own RouteData, set the "controller" and "action", clear the Response, grab this.Context and dump it into a new RequestContext, create a new IController using ControllerBuilder using the route data you created before, and then rewrite your path and execute the controller using the new request context. Somewhere in there you'd have to dump in your ModelState to carry over. I haven't tried it, and that seems overkill.

这篇关于如何在ASP.NET MVC子操作处理程序返回模型状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆