我有一个MVC web API项目,其中包含文件夹视图/表单,我想将视图作为HTML字符串读取,包括部分视图;
这是我从视图中获取HTML字符串的代码
public class HtmlActionResult : IHttpActionResult
{
private const string ViewDirectory = @"..\Views\Forms";
private readonly string _view;
private readonly dynamic _model;
public HtmlActionResult(string viewName, dynamic model)
{
_view = LoadView(viewName);
_model = model;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var parsedView = RazorEngine.Razor.Parse(_view, _model);
response.Content = new StringContent(parsedView);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return Task.FromResult(response);
}
private static string LoadView(string name)
{
string path = HttpContext.Current.Server.MapPath("~/views/forms");
path = Path.Combine(path, name + ".cshtml");
string view = string.Empty;
if (File.Exists(path))
view = File.ReadAllText(path);
return view;
}
以下是执行的方式:
var htmlAction = new HtmlActionResult("MyView", MyModel);
var response = await htmlAction.ExecuteAsync(new CancellationToken());
MyView包含名为separator.cshtml
如何渲染局部视图separator.cshtml
,我尝试添加如下所述的参考解析器:
Reference resolver for Rezor Engine
并在获取HTML响应字符串之前添加以下代码:
var config = new TemplateServiceConfiguration();
config.ReferenceResolver = new MyIReferenceResolver();
var service = RazorEngineService.Create(config);