【问题标题】:How I can get the string result of a view passing it the model in a controller action in Asp.net MVC如何在 Asp.net MVC 的控制器操作中获取将模型传递给它的视图的字符串结果
【发布时间】:2013-07-11 05:52:02
【问题描述】:

我需要从特定视图加载生成的字符串,以便将其加载到控制器操作中的 XmlDocument 对象中,以便对其进行其他操作。

我想将该视图用作模板,它会生成 SVG 图像。

得到结果后,我需要将结果作为 XMLDocument 传递给第三方 dll,该 dll 接受 XMLDocument 并将其转换为位图图像

你怎么能做到这一点?这应该是一个简单的操作,但我没有找到线索。

提前致谢

【问题讨论】:

  • 浏览量没有result,能详细点吗?
  • 你的问题不够清楚。你想达到什么目的?
  • 我真的不明白你想要实现的目标。您想从视图生成 XML 并将其结果保存在文件中吗?
  • 我更新了我的问题以澄清这一点。

标签: xml asp.net-mvc


【解决方案1】:

这个问题确实不清楚。

如果你想将渲染的 html 作为字符串,你可以使用以下扩展方法获取视图的字符串输出:

public static string RenderPartialView(this Controller controller, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

    controller.ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

像这样使用它(在动作的代码中):

var model = [whatever is the model that is used by the view]
var renderedView = this.RenderPartialView("Path to the view", model);

然后您可以使用Html Agility Pack 将此字符串解析为文档。您可以在this answer 了解如何操作。

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多