Core中使用Razor视图引擎渲染视图为字符串
- }
- <!DOCTYPE html>
- <html>
- <head>
- <title>Render view to string</title>
- </head>
- <body>
- <div>
- @Model.Name
- </div>
- </body>
- </html>
3、修改HomeController
- public class HomeController : Controller
- {
- private IViewRenderService _viewRenderService;
- public HomeController(IViewRenderService viewSendeRenderService)
- {
- _viewRenderService = viewSendeRenderService;
- }
- public async Task<IActionResult> Index()
- {
- var user = new MyUserViewModel { Name = "hello world" };
- var result = await _viewRenderService.RenderToStringAsync("Home/Template1", user);
- return Content(result);
- }
- }
4、别忘了Startup
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddScoped<IViewRenderService, ViewRenderService>();
- services.AddMvc();
- }
四、写在最后
最后我只能说在ASP.NET Core中是万物皆DI啊,其实ASP.NET Core中的实现早就为我们想好了这些功能,只是改变了使用方式。
GitHub:https://github.com/maxzhang1985/YOYOFx 如果觉还可以请Star下, 欢迎一起交流。
.NET Core 开源学习群: 214741894