解析html字符串 c,ASP.NET Core 后台方法中解析视图(View)获取生成的html字符串

1、添加将视图(View)生成html字符串的扩展方法using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Rendering;

using Microsoft.AspNetCore.Mvc.ViewEngines;

using Microsoft.AspNetCore.Mvc.ViewFeatures;

using System.IO;

using System.Threading.Tasks;

namespace CC.Web.Helpers

{

public static class ControllerExtensions

{

public static async Task RenderViewAsync(this Controller controller, string viewName, TModel model, bool partial = false)

{

if (string.IsNullOrEmpty(viewName))

{

viewName = controller.ControllerContext.ActionDescriptor.ActionName;

}

controller.ViewData.Model = model;

using (var writer = new StringWriter())

{

IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;

ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);

if (viewResult.Success == false)

{

return $"A view with the name {viewName} could not be found";

}

ViewContext viewContext = new ViewContext(

controller.ControllerContext,

viewResult.View,

controller.ViewData,

controller.TempData,

writer,

new HtmlHelperOptions()

);

await viewResult.View.RenderAsync(viewContext);

return writer.GetStringBuilder().ToString();

}

}

}

}

2、上面RenderViewAsync扩展方法的使用方法

1)对于View视图使用代码viewHtml = await this.RenderViewAsync("Report", model);

2)对于PartialView视图使用代码partialViewHtml = await this.RenderViewAsync("Report", model, true);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值