gpt4 book ai didi

c# - ASP.NET CORE 将 Razor View 渲染为带有 Controller 参数的字符串

转载 作者:行者123 更新时间:2023-12-05 02:50:03 26 4
gpt4 key购买 nike

我需要将部分 View 呈现为字符串。为此,我使用以下 Helper 类:

public static string RenderRazorViewToString(Controller controller, string viewName, object model = null)
{
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
IViewEngine viewEngine =
controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as
ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, false);

ViewContext viewContext = new ViewContext(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
}

这行得通,但我现在需要一个同样接受参数列表的类似方法。我想呈现为字符串的 View 是通过以下 Controller 方法调用的:

public Task<IActionResult> IndexPartial(string? searchValue, string? filterValue)
{
IQueryable<Invoice> query
....Manipulate query by searchValue and filterValue
return PartialView("IndexPartial",await query.ToListAsync());
}

当我调用 Helper.RenderRazorViewToString(controller, "IndexPartial", model) 时,我必须传递 stringValue 和 FilterValue。

有人知道如何实现吗?

最佳答案

RenderRazorViewToString的用法我想你应该明白了,这个方法调用的代码如下:

Helper.RenderRazorViewToString(controller, "PartialViewName", model);

第二个参数不是方法名,是局部 View 名,不会到IndexPartial方法

你想要的是将带有模型的部分 View 解析为字符串。模型数据通过searchValuefilterValue操作查询得到。

为了满足您的要求,您需要做的应该如下所示:

public string IndexPartial(string? searchValue, string? filterValue)
{
var model = _context.Pupils
.Where(a => a.Name.Contains(searchValue)&& a.Email.Contains(filterValue))
.FirstOrDefault(); //Manipulate query by searchValue and filterValue

//pass the correct model to the RenderRazorViewToString method
//then it would render the partial view to the correct string
var data = Helper.RenderRazorViewToString(this, "PartialViewName", model);
return data;
}

结果: enter image description here

关于c# - ASP.NET CORE 将 Razor View 渲染为带有 Controller 参数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63780705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com