【问题标题】:asp.net mvc 5 action filter that renders view as json将视图呈现为 json 的 asp.net mvc 5 操作过滤器
【发布时间】:2016-10-25 19:30:02
【问题描述】:

在我的 asp.net mvc 5 应用程序中,是否可以编写一个动作过滤器来拦截 ActionResult 并返回一个 JsonResult,其中包含作为 html 字符串呈现的视图和作为 json 的模型?

考虑这个伪代码:

JSON(new { html = ViewAsHTMLString, model = this.ViewsViewModel })

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-5 action-filter


    【解决方案1】:

    我在我的应用程序中使用了这样一个简单的 ActionResult 方法:

     return Json(new
                                            {
                                                result = "fail",
                                                html = Extensions.RenderViewToString(ControllerContext, "_Partial_CreatePageContainer", model),
                                                errors = "This page already exists."
                                            });
    

    然后我创建了 2 个扩展方法来处理视图渲染:

     public static string RenderViewToString(ControllerContext context, string viewName, object model)
            {
                if (string.IsNullOrEmpty(viewName))
                    viewName = context.RouteData.GetRequiredString("action");
    
                var viewData = new ViewDataDictionary(model);
    
                using (var sw = new StringWriter())
                {
                    var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                    var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
                    viewResult.View.Render(viewContext, sw);
    
                    return sw.GetStringBuilder().ToString();
                }
            }
            public static string RenderViewToString(ControllerContext context, string viewName)
            {
                if (string.IsNullOrEmpty(viewName))
                    viewName = context.RouteData.GetRequiredString("action");
    
                var viewData = new ViewDataDictionary();
    
                using (var sw = new StringWriter())
                {
                    var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                    var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
                    viewResult.View.Render(viewContext, sw);
    
                    return sw.GetStringBuilder().ToString();
                }
            }
    

    【讨论】:

    • 但这看起来只是在修改返回值。我正在寻找一种方法来作为操作过滤器执行此操作,以便在不是 ajax 请求时可以返回View。不过这很有帮助!
    • 碰巧,您是否使用 Jquery 处理您的 Ajax 请求?
    • 我正在使用 jQuery 并且正在利用 isAjaxRequest
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多