How can I save HTML of rendered View?











up vote
1
down vote

favorite












Basically User enters page, generates report and decides whether it should be saved or not.



If yes, then I have to save this html as static html file.



It'd be really nice if that was something like:



public IActionResult GetReport()
{
(...)
string html = View(model).ToString();
save_to_database(html);
return View(model);
}


But, the only solution that I managed to find is putting button on that page
which executes JavaScript like this one:



var html = new XMLSerializer().serializeToString(document); 

sendHTMLViaAPI(html);


and sending that html to API via post.



So, I'm curious whether there are C#-ish ways to do it? in Controller's method.



Also: Is that potentially dangerous? E.g. session things can be saved in that html file or user can send content of non-HTML file via API...










share|improve this question
























  • possible duplicate: stackoverflow.com/questions/6558204/…
    – JohnB
    Nov 14 at 7:47










  • Well, nothing have changed over 8 years? :)
    – Joelty
    Nov 14 at 7:55










  • Sorry, is this your goal: Converting HTML code in the razor page to string?
    – Foo
    Nov 14 at 8:07










  • @TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
    – Joelty
    Nov 14 at 8:10















up vote
1
down vote

favorite












Basically User enters page, generates report and decides whether it should be saved or not.



If yes, then I have to save this html as static html file.



It'd be really nice if that was something like:



public IActionResult GetReport()
{
(...)
string html = View(model).ToString();
save_to_database(html);
return View(model);
}


But, the only solution that I managed to find is putting button on that page
which executes JavaScript like this one:



var html = new XMLSerializer().serializeToString(document); 

sendHTMLViaAPI(html);


and sending that html to API via post.



So, I'm curious whether there are C#-ish ways to do it? in Controller's method.



Also: Is that potentially dangerous? E.g. session things can be saved in that html file or user can send content of non-HTML file via API...










share|improve this question
























  • possible duplicate: stackoverflow.com/questions/6558204/…
    – JohnB
    Nov 14 at 7:47










  • Well, nothing have changed over 8 years? :)
    – Joelty
    Nov 14 at 7:55










  • Sorry, is this your goal: Converting HTML code in the razor page to string?
    – Foo
    Nov 14 at 8:07










  • @TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
    – Joelty
    Nov 14 at 8:10













up vote
1
down vote

favorite









up vote
1
down vote

favorite











Basically User enters page, generates report and decides whether it should be saved or not.



If yes, then I have to save this html as static html file.



It'd be really nice if that was something like:



public IActionResult GetReport()
{
(...)
string html = View(model).ToString();
save_to_database(html);
return View(model);
}


But, the only solution that I managed to find is putting button on that page
which executes JavaScript like this one:



var html = new XMLSerializer().serializeToString(document); 

sendHTMLViaAPI(html);


and sending that html to API via post.



So, I'm curious whether there are C#-ish ways to do it? in Controller's method.



Also: Is that potentially dangerous? E.g. session things can be saved in that html file or user can send content of non-HTML file via API...










share|improve this question















Basically User enters page, generates report and decides whether it should be saved or not.



If yes, then I have to save this html as static html file.



It'd be really nice if that was something like:



public IActionResult GetReport()
{
(...)
string html = View(model).ToString();
save_to_database(html);
return View(model);
}


But, the only solution that I managed to find is putting button on that page
which executes JavaScript like this one:



var html = new XMLSerializer().serializeToString(document); 

sendHTMLViaAPI(html);


and sending that html to API via post.



So, I'm curious whether there are C#-ish ways to do it? in Controller's method.



Also: Is that potentially dangerous? E.g. session things can be saved in that html file or user can send content of non-HTML file via API...







c# html asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 at 8:19

























asked Nov 14 at 7:34









Joelty

747




747












  • possible duplicate: stackoverflow.com/questions/6558204/…
    – JohnB
    Nov 14 at 7:47










  • Well, nothing have changed over 8 years? :)
    – Joelty
    Nov 14 at 7:55










  • Sorry, is this your goal: Converting HTML code in the razor page to string?
    – Foo
    Nov 14 at 8:07










  • @TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
    – Joelty
    Nov 14 at 8:10


















  • possible duplicate: stackoverflow.com/questions/6558204/…
    – JohnB
    Nov 14 at 7:47










  • Well, nothing have changed over 8 years? :)
    – Joelty
    Nov 14 at 7:55










  • Sorry, is this your goal: Converting HTML code in the razor page to string?
    – Foo
    Nov 14 at 8:07










  • @TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
    – Joelty
    Nov 14 at 8:10
















possible duplicate: stackoverflow.com/questions/6558204/…
– JohnB
Nov 14 at 7:47




possible duplicate: stackoverflow.com/questions/6558204/…
– JohnB
Nov 14 at 7:47












Well, nothing have changed over 8 years? :)
– Joelty
Nov 14 at 7:55




Well, nothing have changed over 8 years? :)
– Joelty
Nov 14 at 7:55












Sorry, is this your goal: Converting HTML code in the razor page to string?
– Foo
Nov 14 at 8:07




Sorry, is this your goal: Converting HTML code in the razor page to string?
– Foo
Nov 14 at 8:07












@TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
– Joelty
Nov 14 at 8:10




@TânNguyễn Convert View(model) to string (which is HTML). Basically the page that is rendered for user, I'd also want to save e.g in string. string html = View(model).ToString() something like this.
– Joelty
Nov 14 at 8:10












1 Answer
1






active

oldest

votes

















up vote
2
down vote













If I understand you meant correctly, this solution may be what you're looking for:



[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };

// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}


In the file GetHTML.cshtml:



@model ModelClass 
<div>
Content: @Model.Content
</div>


In the clientside, when user wants to get the HTML as string, you can try to use jquery to get it:



$.post('/home/gethtml').done(function (html) {
// html is a string here..

// <div>
// Content: Hi!
// </div>

$('body').append(html);
});




Or creating your custom service:



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>();




Usage:



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);

//...
}
}





share|improve this answer























  • Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
    – Joelty
    Nov 14 at 8:18










  • @Joelty I've updated with a service to get the HTML string in the controller.
    – Foo
    Nov 14 at 8:31











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295126%2fhow-can-i-save-html-of-rendered-view%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote













If I understand you meant correctly, this solution may be what you're looking for:



[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };

// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}


In the file GetHTML.cshtml:



@model ModelClass 
<div>
Content: @Model.Content
</div>


In the clientside, when user wants to get the HTML as string, you can try to use jquery to get it:



$.post('/home/gethtml').done(function (html) {
// html is a string here..

// <div>
// Content: Hi!
// </div>

$('body').append(html);
});




Or creating your custom service:



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>();




Usage:



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);

//...
}
}





share|improve this answer























  • Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
    – Joelty
    Nov 14 at 8:18










  • @Joelty I've updated with a service to get the HTML string in the controller.
    – Foo
    Nov 14 at 8:31















up vote
2
down vote













If I understand you meant correctly, this solution may be what you're looking for:



[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };

// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}


In the file GetHTML.cshtml:



@model ModelClass 
<div>
Content: @Model.Content
</div>


In the clientside, when user wants to get the HTML as string, you can try to use jquery to get it:



$.post('/home/gethtml').done(function (html) {
// html is a string here..

// <div>
// Content: Hi!
// </div>

$('body').append(html);
});




Or creating your custom service:



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>();




Usage:



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);

//...
}
}





share|improve this answer























  • Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
    – Joelty
    Nov 14 at 8:18










  • @Joelty I've updated with a service to get the HTML string in the controller.
    – Foo
    Nov 14 at 8:31













up vote
2
down vote










up vote
2
down vote









If I understand you meant correctly, this solution may be what you're looking for:



[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };

// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}


In the file GetHTML.cshtml:



@model ModelClass 
<div>
Content: @Model.Content
</div>


In the clientside, when user wants to get the HTML as string, you can try to use jquery to get it:



$.post('/home/gethtml').done(function (html) {
// html is a string here..

// <div>
// Content: Hi!
// </div>

$('body').append(html);
});




Or creating your custom service:



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>();




Usage:



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);

//...
}
}





share|improve this answer














If I understand you meant correctly, this solution may be what you're looking for:



[HttpPost]
public IActionResult GetHTML()
{
var model = new ModelClass() { Content = "Hi!" };

// or
// return PartialView("GetHTML", model);
return PartialView(nameof(GetHTML), model);
}


In the file GetHTML.cshtml:



@model ModelClass 
<div>
Content: @Model.Content
</div>


In the clientside, when user wants to get the HTML as string, you can try to use jquery to get it:



$.post('/home/gethtml').done(function (html) {
// html is a string here..

// <div>
// Content: Hi!
// </div>

$('body').append(html);
});




Or creating your custom service:



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>();




Usage:



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);

//...
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 at 8:57

























answered Nov 14 at 8:17









Foo

1




1












  • Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
    – Joelty
    Nov 14 at 8:18










  • @Joelty I've updated with a service to get the HTML string in the controller.
    – Foo
    Nov 14 at 8:31


















  • Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
    – Joelty
    Nov 14 at 8:18










  • @Joelty I've updated with a service to get the HTML string in the controller.
    – Foo
    Nov 14 at 8:31
















Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
– Joelty
Nov 14 at 8:18




Yea, that's one of solutions, but is there an C# way to do it? e.g save it while being in controller's method
– Joelty
Nov 14 at 8:18












@Joelty I've updated with a service to get the HTML string in the controller.
– Foo
Nov 14 at 8:31




@Joelty I've updated with a service to get the HTML string in the controller.
– Foo
Nov 14 at 8:31


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295126%2fhow-can-i-save-html-of-rendered-view%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?