【问题标题】:ASP.NET MVC render partial view to a string to return with JSON [duplicate]ASP.NET MVC 将部分视图呈现为字符串以返回 JSON [重复]
【发布时间】:2013-03-13 09:08:17
【问题描述】:

所以我有一个完整的方法,我在整个网站上都使用它:

public PartialViewResult GetBlogEntries(int itemsToTake = 5)
{
    ...
    return PartialView("_BlogPost", model);
}

现在我想从我的 javascript 中以 JSON 形式获取它。

public JsonResult GetBlogPostJson()
{      
    var blogEntry = GetBlogEntries(1);
    var lastEntryId = GetLastBlogEntryId();
    return Json(new {Html = blogEntry, LastEntryId = lastEntryId}, JsonRequestBehavior.AllowGet);
}

想法是这样得到它:

$.ajax({
            url: '/Blog/GetBlogPostJson',
            dataType: 'json',
            success: function (data) {
                var lastEntryId = data.LastEntryId;
                var html = data.Html;
                ...
            }
        }); 

问题是这当然不会产生一个字符串,而是一个 PartialViewResult。

问题是,我怎样才能将 PartialViewResult 解析成可以用 JSON 发回的 html?

【问题讨论】:

  • 如果我错了请纠正我,你想生成 HTML,然后从这个 HTML 中获取一个 Id,最后以 JSON 格式发送 Id 和 HTML?
  • 是和不是。 GetBlogEntries() 方法创建了一个局部视图,我从网页上的各个位置调用该视图。但是,它不会在任何地方打印出 ID。所以我需要单独得到它。然后将 html 和 id 发送给调用者。客户端上的 javascript 将确保仅在有新的博客条目时才获取新的博客条目。

标签: javascript c# jquery asp.net-mvc asp.net-mvc-4


【解决方案1】:

我大约在 6 个月前经历过这个。目标是使用部分填充 jquery 弹出对话框。

问题是视图引擎想要以自己尴尬的顺序渲染它们......

试试这个。 LMK 如果需要澄清。

    public static string RenderPartialViewToString(Controller thisController, string viewName, object model)
    {
        // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way)
        thisController.ViewData.Model = model;

        // initialize a string builder
        using (StringWriter sw = new StringWriter())
        {
            // find and load the view or partial view, pass it through the controller factory
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw);

            // render it
            viewResult.View.Render(viewContext, sw);

            //return the razorized view/partial-view as a string
            return sw.ToString();
        }
    }

【讨论】:

  • 我如何通过(Controller thisController),你能告诉我如何使用你的方法吗?
  • 这可行,但它不是可单元测试的。 :(
  • @DanHunex,RenderPartialViewToString 不容易进行单元测试。但是,如果您对控制器进行单元测试,这是一次性的步骤。
  • @DaveA 是的,我测试了我的控制器。我想测试我的“GetBlogPostJson”
  • @Sandeep,传递调用控制器、字符串中的视图名称和传递模型。该方法将从您的 Controller 运行 View Factory 以生成 HTML 字符串
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多