Snæ*_*ørn 3 c# razorengine asp.net-core razor-pages asp.net-core-3.1
IsDevelopment().我正在使用 ASP.NET Core 3.1
我想我会尝试新的Razor Pages,因为它们被宣传为非常简单。
@page
@using MyProject.Pages.Pdf
@model IndexModel
<h2>Test</h2>
<p>
@Model.Message
</p>
Run Code Online (Sandbox Code Playgroud)
namespace MyProject.Pages.Pdf
{
public class IndexModel : PageModel
{
private readonly MyDbContext _context;
public IndexModel(MyDbContext context)
{
_context = context;
}
public string Message { get; private set; } = "PageModel in C#";
public async Task<IActionResult> OnGetAsync()
{
var count = await _context.Foos.CountAsync();
Message += $" Server time is { DateTime.Now } and the Foo count is { count }";
return Page();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于浏览器 - 是的!
我发现Render a Razor Page to string似乎可以做我想要的。
但这就是麻烦开始的地方:(
首先,我觉得很奇怪,当你发现页面通过_razorViewEngine.FindPage它不知道如何填充ViewContext或Model。我认为的工作IndexModel是填充这些。我希望可以向 ASP.NET 请求IndexModel页面,就是这样。
无论如何……下一个问题。为了呈现页面,我必须手动创建一个,ViewContext并且必须为它提供一个Model. 但 Page 是模型,因为它是一个页面,所以它不是一个简单的 ViewModel。它依赖于 DI 并且它期望OnGetAsync()被执行以填充模型。这几乎是一个catch-22。
我还尝试通过获取视图而不是页面,_razorViewEngine.FindView但这也需要一个模型,所以我们又回到了 catch-22。
另一个问题。调试/调整页面的目的是轻松查看生成的内容。但是如果我必须创建一个Model外部,IndexModel那么它不再代表某处服务中实际生成的内容。
这一切让我怀疑我是否走在正确的道路上。或者我错过了什么?
请参考以下步骤将局部视图渲染为字符串:
向名为 IrazorPartialToStringRenderer.cs 的 Services 文件夹添加一个接口。
public interface IRazorPartialToStringRenderer
{
Task<string> RenderPartialToStringAsync<TModel>(string partialName, TModel model);
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码将 C# 类文件添加到名为 RazorPartialToStringRenderer.cs 的 Services 文件夹:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
namespace RazorPageSample.Services
{
public class RazorPartialToStringRenderer : IRazorPartialToStringRenderer
{
private IRazorViewEngine _viewEngine;
private ITempDataProvider _tempDataProvider;
private IServiceProvider _serviceProvider;
public RazorPartialToStringRenderer(
IRazorViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_viewEngine = viewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
public async Task<string> RenderPartialToStringAsync<TModel>(string partialName, TModel model)
{
var actionContext = GetActionContext();
var partial = FindView(actionContext, partialName);
using (var output = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
partial,
new ViewDataDictionary<TModel>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = model
},
new TempDataDictionary(
actionContext.HttpContext,
_tempDataProvider),
output,
new HtmlHelperOptions()
);
await partial.RenderAsync(viewContext);
return output.ToString();
}
}
private IView FindView(ActionContext actionContext, string partialName)
{
var getPartialResult = _viewEngine.GetView(null, partialName, false);
if (getPartialResult.Success)
{
return getPartialResult.View;
}
var findPartialResult = _viewEngine.FindView(actionContext, partialName, false);
if (findPartialResult.Success)
{
return findPartialResult.View;
}
var searchedLocations = getPartialResult.SearchedLocations.Concat(findPartialResult.SearchedLocations);
var errorMessage = string.Join(
Environment.NewLine,
new[] { $"Unable to find partial '{partialName}'. The following locations were searched:" }.Concat(searchedLocations)); ;
throw new InvalidOperationException(errorMessage);
}
private ActionContext GetActionContext()
{
var httpContext = new DefaultHttpContext
{
RequestServices = _serviceProvider
};
return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
}
}
}
Run Code Online (Sandbox Code Playgroud)
ConfigureServices在Startup类中的方法中注册服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddTransient<IRazorPartialToStringRenderer, RazorPartialToStringRenderer>();
}
Run Code Online (Sandbox Code Playgroud)
使用 RenderPartialToStringAsync() 方法将 Razor 页面呈现为 HTML 字符串:
public class ContactModel : PageModel
{
private readonly IRazorPartialToStringRenderer _renderer;
public ContactModel(IRazorPartialToStringRenderer renderer)
{
_renderer = renderer;
}
public void OnGet()
{
}
[BindProperty]
public ContactForm ContactForm { get; set; }
[TempData]
public string PostResult { get; set; }
public async Task<IActionResult> OnPostAsync()
{
var body = await _renderer.RenderPartialToStringAsync("_ContactEmailPartial", ContactForm); //transfer model to the partial view, and then render the Partial view to string.
PostResult = "Check your specified pickup directory";
return RedirectToPage();
}
}
public class ContactForm
{
public string Email { get; set; }
public string Message { get; set; }
public string Name { get; set; }
public string Subject { get; set; }
public Priority Priority { get; set; }
}
public enum Priority
{
Low, Medium, High
}
Run Code Online (Sandbox Code Playgroud)
调试截图如下:
更详细的步骤,请查看此博客Rendering A Partial View To A String。
我成功破解了它!毕竟我走错了路......解决方案是使用ViewComponent. 但它仍然很时髦!
谢谢
namespace MyProject.ViewComponents
{
public class MyViewComponent : ViewComponent
{
private readonly MyDbContext _context;
public MyViewComponent(MyDbContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var count = await _context.Foos.CountAsync();
var message = $"Server time is { DateTime.Now } and the Foo count is { count }";
return View<string>(message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
视图放置在Pages/Shared/Components/My/Default.cshtml中
@model string
<h2>Test</h2>
<p>
@Model
</p>
Run Code Online (Sandbox Code Playgroud)
@model string
<h2>Test</h2>
<p>
@Model
</p>
Run Code Online (Sandbox Code Playgroud)
注意文件后面没有代码
@page
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent))
Run Code Online (Sandbox Code Playgroud)
@page "{id}"
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent), RouteData.Values["id"])
Run Code Online (Sandbox Code Playgroud)
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
public class RenderViewComponentService
{
private readonly IServiceProvider _serviceProvider;
private readonly ITempDataProvider _tempDataProvider;
private readonly IViewComponentHelper _viewComponentHelper;
public RenderViewComponentService(
IServiceProvider serviceProvider,
ITempDataProvider tempDataProvider,
IViewComponentHelper viewComponentHelper
)
{
_serviceProvider = serviceProvider;
_tempDataProvider = tempDataProvider;
_viewComponentHelper = viewComponentHelper;
}
public async Task<string> RenderViewComponentToStringAsync<TViewComponent>(object args)
where TViewComponent : ViewComponent
{
var viewContext = GetFakeViewContext();
(_viewComponentHelper as IViewContextAware).Contextualize(viewContext);
var htmlContent = await _viewComponentHelper.InvokeAsync<TViewComponent>(args);
using var stringWriter = new StringWriter();
htmlContent.WriteTo(stringWriter, HtmlEncoder.Default);
var html = stringWriter.ToString();
return html;
}
private ViewContext GetFakeViewContext(ActionContext actionContext = null, TextWriter writer = null)
{
actionContext ??= GetFakeActionContext();
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);
var viewContext = new ViewContext(
actionContext,
NullView.Instance,
viewData,
tempData,
writer ?? TextWriter.Null,
new HtmlHelperOptions());
return viewContext;
}
private ActionContext GetFakeActionContext()
{
var httpContext = new DefaultHttpContext
{
RequestServices = _serviceProvider,
};
var routeData = new RouteData();
var actionDescriptor = new ActionDescriptor();
return new ActionContext(httpContext, routeData, actionDescriptor);
}
private class NullView : IView
{
public static readonly NullView Instance = new NullView();
public string Path => string.Empty;
public Task RenderAsync(ViewContext context)
{
if (context == null) { throw new ArgumentNullException(nameof(context)); }
return Task.CompletedTask;
}
}
}
Run Code Online (Sandbox Code Playgroud)
@page
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent))
Run Code Online (Sandbox Code Playgroud)
非常不幸的是,注入的东西IViewComponentHelper不能开箱即用。
所以我们做了这个非常不直观的事情来让它发挥作用。
@page "{id}"
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent), RouteData.Values["id"])
Run Code Online (Sandbox Code Playgroud)
这会导致一系列奇怪的事情,例如假货ActionContext,并且ViewContext需要 aTextWriter但它不用于任何用途!事实上这个洞ViewContext根本没有被使用。它只需要存在:(
另外NullView...由于某种原因Microsoft.AspNetCore.Mvc.ViewFeatures.NullView,Internal我们基本上必须将其复制/粘贴到我们自己的代码中。
也许将来会有所改善。
无论如何:在我看来,这比使用它更简单,IRazorViewEngine它几乎出现在每个网络搜索中:)
| 归档时间: |
|
| 查看次数: |
1688 次 |
| 最近记录: |