I have an MVC web API project that includes a folder views/forms, and i want to read the view as HTML string including the partial views;
this is my code to get the HTML string from the view
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;
}
Here's how its Executed :
var htmlAction = new HtmlActionResult("MyView", MyModel);
var response = await htmlAction.ExecuteAsync(new CancellationToken());
MyView contains a partial view in the same folder (views/forms) called separator.cshtml
How can i render the partial view separator.cshtml, i tried adding a reference resolver like stated here:
Reference resolver for Rezor Engine
and added the following code before getting the HTML response string:
var config = new TemplateServiceConfiguration();
config.ReferenceResolver = new MyIReferenceResolver();
var service = RazorEngineService.Create(config);