在.NET Core中以字符串形式返回视图

在.NET Core中以字符串形式返回视图,第1张

在.NET Core中以字符串形式返回视图

感谢Paris
Polyzos
及其文章。

我在这里重新发布他的代码,以防万一原始帖子因任何原因被删除。

Service
文件中创建
viewToString.cs
如下代码:

using System;using System.IO;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.ViewFeatures;using Microsoft.AspNetCore.Routing;     namespace WebApplication.Services{        public interface IViewRenderService        {            Task<string> RenderToStringAsync(string viewName, object model);        }             public class ViewRenderService : IViewRenderService        {            private readonly IRazorViewEngine _razorViewEngine;            private readonly ITempDataProvider _tempDataProvider;            private readonly IServiceProvider _serviceProvider;                 public ViewRenderService(IRazorViewEngine razorViewEngine,                ITempDataProvider tempDataProvider,                IServiceProvider serviceProvider)            {                _razorViewEngine = razorViewEngine;                _tempDataProvider = tempDataProvider;                _serviceProvider = serviceProvider;            }                 public async Task<string> RenderToStringAsync(string viewName, object model)            {                var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };                var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());                     using (var sw = new StringWriter())                {                    var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);                         if (viewResult.View == null)                    {                        throw new ArgumentNullException($"{viewName} does not match any available view");                    }                         var viewDictionary = new ViewDataDictionary(new EmptyModelmetadataProvider(), new ModelStateDictionary())                    {                        Model = model                    };                         var viewContext = new ViewContext(                        actionContext,                        viewResult.View,                        viewDictionary,                        new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),                        sw,                        new HtmlHelperOptions()                    );                         await viewResult.View.RenderAsync(viewContext);                    return sw.ToString();                }            }        }}

2. 将服务添加到

Startup.cs
文件中,如下所示:

using WebApplication.Services;public void ConfigureServices(IServiceCollection services){    ...    services.AddScoped<IViewRenderService, ViewRenderService>();}

3. 添加

"preserveCompilationContext":true
buildOptions
中的
project.json
,因此文件如下所示:

{    "version": "1.0.0-*",    "buildOptions": {    "debugType": "portable",    "emitEntryPoint": true,    "preserveCompilationContext": true    },    "dependencies": {    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",    "Microsoft.AspNetCore.Mvc": "1.0.1"    },    "frameworks": {    "netcoreapp1.0": {        "dependencies": {        "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1"        }        },        "imports": "dnxcore50"    }    }}

4. 定义您

model
,例如:

public class InviteViewModel {    public string   UserId {get; set;}    public string   UserName {get; set;}    public string   ReferralCode {get; set;}    public int  Credits {get; set;}}

5. 创建您

Invite.cshtml
示例

@{    ViewData["Title"] = "Contact";}@ViewData["Title"].user id: @Model.UserId

6.

Controller

一个。 首先定义以下内容:

private readonly IViewRenderService _viewRenderService;public RenderController(IViewRenderService viewRenderService){    _viewRenderService = viewRenderService;}

b。 调用并返回带有模型的视图,如下所示:

var result = await _viewRenderService.RenderToStringAsync("Email/Invite", viewModel);return Content(result);

C。 FULL控制器的示例如下:

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using WebApplication.Services;namespace WebApplication.Controllers{    [Route("render")]    public class RenderController : Controller    {        private readonly IViewRenderService _viewRenderService;        public RenderController(IViewRenderService viewRenderService)        { _viewRenderService = viewRenderService;        }    [Route("invite")]    public async Task<IActionResult> RenderInviteView()    {        ViewData["Message"] = "Your application description page.";        var viewModel = new InviteViewModel        { UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78", UserName = "Hasan", ReferralCode = "55e12b710f78", Credits = 10        };             var result = await _viewRenderService.RenderToStringAsync("Email/Invite", viewModel);        return Content(result);    }    public class InviteViewModel {        public string   UserId {get; set;}        public string   UserName {get; set;}        public string   ReferralCode {get; set;}        public int  Credits {get; set;}    } }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5559742.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存