欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET MVC后台获得VIEW对应的html

程序员文章站 2023-11-14 09:01:22
一、.Net Core Mvc下获得 建立一个帮助类,如下: 后台调用方法 参考自:https://www.cjavapy.com/article/147/ 二、.Net Mvc下获得 ......

一、.net core mvc下获得

    建立一个帮助类,如下:

using microsoft.aspnetcore.mvc;
using microsoft.aspnetcore.mvc.rendering;
using microsoft.aspnetcore.mvc.viewengines;
using microsoft.aspnetcore.mvc.viewfeatures;
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.threading.tasks;

namespace netcoreportal.models
{
    public class viewhtmlhelper
    {
        public static string converttostring(controller controller, string viewname, object viewmodel, bool ismainpage)
        {
            controller.viewdata.model = viewmodel;
            using (stringwriter sw = new stringwriter())
            {
                iviewengine viewengine = controller.httpcontext.requestservices.getservice(typeof(icompositeviewengine)) as icompositeviewengine;
                viewengineresult viewengineresult = viewengine.findview(controller.controllercontext, viewname, ismainpage);
                if (viewengineresult.success)
                {
                    viewcontext viewcontext = new viewcontext(
                        controller.controllercontext,
                        viewengineresult.view,
                        controller.viewdata,
                        controller.tempdata,
                       sw,
                       new htmlhelperoptions()
                        );
                    viewengineresult.view.renderasync(viewcontext);
                    return sw.getstringbuilder().tostring();
                }
                else
                {
                    return $"视图{viewname}不存在";
                }
            }
        }
    }
}

    后台调用方法

public contentresult viewtostringdemo()
{
    string strview = viewhtmlhelper.converttostring(this, "index", "", true);
    return content(strview);
}

 参考自:

 

二、.net mvc下获得

/// <summary>
/// 获得laytreegrid视图的html内容
/// </summary>
/// <returns></returns>
public contentresult viewtext()
{
     string html = string.empty;
     iview view = viewengines.engines.findview(this.controllercontext, "laytreegrid", null).view;

     viewdatadictionary vdd = new viewdatadictionary();
     tempdatadictionary tdd = new tempdatadictionary();
     using (system.io.stringwriter sw = new system.io.stringwriter())
     {
         viewcontext viewcontext = new viewcontext(this.controllercontext, view, vdd, tdd, sw);
         viewcontext.view.render(viewcontext, sw);
         html = sw.tostring();
     }
     return content(html);
}