Если я понимаю, что вы имели в виду правильно, это решение может быть тем, что вы ищете:
[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };
// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}
В файле GetHTML.cshtml
:
@model ModelClass
<div>
Content: @Model.Content
</div>
На стороне клиента,когда пользователь хочет получить HTML-код в виде строки, вы можете попытаться использовать jquery для его получения:
$.post('/home/gethtml').done(function (html) {
// html is a string here..
// <div>
// Content: Hi!
// </div>
$('body').append(html);
});
Или создайте свой собственный сервис:
ViewRender.cs
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;
using System;
using System.IO;
public class ViewRender : IViewRender
{
private IRazorViewEngine _viewEngine;
private ITempDataProvider _tempDataProvider;
private IServiceProvider _serviceProvider;
public ViewRender(
IRazorViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_viewEngine = viewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
public string Render(string name)
{
var actionContext = GetActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, name, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
}
var view = viewEngineResult.View;
using (var output = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
view,
new ViewDataDictionary<string>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = null
},
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
output,
new HtmlHelperOptions());
view.RenderAsync(viewContext).GetAwaiter().GetResult();
return output.ToString();
}
}
public string Render<TModel>(string name, TModel model)
{
var actionContext = GetActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, name, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
}
var view = viewEngineResult.View;
using (var output = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
view,
new ViewDataDictionary<TModel>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = model
},
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
output,
new HtmlHelperOptions());
view.RenderAsync(viewContext).GetAwaiter().GetResult();
return output.ToString();
}
}
private ActionContext GetActionContext()
{
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = _serviceProvider;
return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
}
}
IViewRender.cs :
public interface IViewRender
{
string Render(string name);
string Render<TModel>(string name, TModel model);
}
Startup.cs :
services.AddTransient<IViewRender, ViewRender>();
Использование:
public class HomeController : Controller
{
private readonly IViewRender _viewRender { get; set; }
public HomeController(IViewRender viewRender)
{
_viewRender = viewRender;
}
public IActionResult GetHTML()
{
string htmlWithoutModel = _viewRender.Render("Home/GetHTML");
var model = new ModelClass() { Content = "Hi!" };
string htmlWithModel = _viewRender.Render<ModelClass>("Home/GetHTML", model);
//...
}
}