转换PartialView为HTML [英] Convert PartialView to HTML

查看:166
本文介绍了转换PartialView为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有可能转换

  PartialView(_产品,型号)

HTML ,所以我们可以把它带回 JSON <? / p>

 返回JSON(结果,JsonRequestBehavior.AllowGet); 


解决方案

当然,把下面的方法在共享控制器或一个辅助类。它会在HTML返回渲染视图,使用自explainatory:

 公共静态字符串RenderViewToString(ControllerContext背景下,字符串的viewName,对象模型)
{
如果(string.IsNullOrEmpty(的viewName))
的viewName = context.RouteData.GetRequiredString(行动);

变种可视数据=新的ViewDataDictionary(模型);

使用(VAR SW =新的StringWriter())
{
变种的ViewResult = ViewEngines.Engines.FindPartialView(背景下,的viewName);
变种viewContext =新ViewContext(背景下,viewResult.View,可视数据,新TempDataDictionary(),SW);
viewResult.View.Render(viewContext,SW);

返回sw.GetStringBuilder()的ToString()。
}
}


I am just wondering if it is possible to convert

PartialView("_Product", model)

to html so we can send it back with JSON ?

return Json(result, JsonRequestBehavior.AllowGet);

解决方案

Absolutely, put the following method in a shared controller or a helper class. It will return the rendered view in HTML, the usage is self explainatory:

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();
        }
    }

这篇关于转换PartialView为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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