Skip to content

Commit

Permalink
Merge pull request #52 from mobiletonster/feature/add-render-partial-…
Browse files Browse the repository at this point in the history
…view

Added option to RenderPartialAsync when you don't need a layout page …
  • Loading branch information
soundaranbu authored Nov 13, 2022
2 parents aa48f1a + 1f6380d commit 1255bf3
Show file tree
Hide file tree
Showing 11 changed files with 222 additions and 167 deletions.
17 changes: 10 additions & 7 deletions examples/Mvc/ExampleWebApp.Net6_0/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
using System.Diagnostics;
using ExampleWebApp.Net6_0.Models;
using Microsoft.AspNetCore.Mvc;
using ExampleWebApp.Net6_0.Models;
using Razor.Templating.Core;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using System.Diagnostics;

namespace ExampleWebApp.Net6_0.Controllers;

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IRazorTemplateEngine _engine;

public HomeController(ILogger<HomeController> logger, IActionContextAccessor actionContext, IRazorTemplateEngine engine)
public HomeController(IRazorTemplateEngine engine)
{
_logger = logger;
_engine = engine;
}

Expand All @@ -30,6 +27,12 @@ public async Task<IActionResult> RenderRcl()
var html = await _engine.RenderAsync("~/Views/ExampleViewWithTagHelpers.cshtml");
return Content(html);
}
public async Task<IActionResult> RenderPartialTest()
{
var testval = "This will get added to the partial view";
var html = await _engine.RenderPartialAsync("~/Views/Home/_PartialTest.cshtml", testval);
return Content(html);
}

public IActionResult Privacy()
{
Expand All @@ -39,6 +42,6 @@ public IActionResult Privacy()
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
9 changes: 8 additions & 1 deletion examples/Mvc/ExampleWebApp.Net6_0/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
</div>

<ul>
<li><a href="/home/RenderRcl">Render content using templating engine</a></li>
<li><a href="/home/RenderPartialTest">Render partial content using templating engine</a></li>
</ul>


Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
var testVal = Model as string;
}
<h1>This is a partial page</h1>
<h2>@testVal</h2>
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
<div>Plain text: @Model?.PlainText</div>
<div>ViewBag data: @ViewBag?.Value1</div>
<div>ViewData data: @ViewData["Value2"]</div>
@Html.Partial("ExamplePartialView.cshtml", Model)
@Html.Partial("_ExamplePartialView.cshtml", Model)
</body>
</html>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@model ExampleRazorTemplatesLibrary.Models.ExampleModel

<div>Partial view</div>
<div>Html content: @Html.Raw(Model?.HtmlContent)</div>
@model ExampleRazorTemplatesLibrary.Models.ExampleModel

<div>Partial view</div>
<div>Html content: @Html.Raw(Model?.HtmlContent)</div>
15 changes: 12 additions & 3 deletions src/Razor.Templating.Core/IRazorTemplateEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@ namespace Razor.Templating.Core
public interface IRazorTemplateEngine
{
/// <summary>
/// Renders View(.cshtml) To String
/// Renders the Razor View(.cshtml) To String
/// </summary>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view bag or view data</param>
/// <returns></returns>
Task<string> RenderAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null);
/// <returns>Rendered HTML string of the view</returns>
Task<string> RenderAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null);

/// <summary>
/// Renders the Razor View(.cshtml) Without Layout to String
/// </summary>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view bag or view data</param>
/// <returns>Rendered HTML string of the view</returns>
Task<string> RenderPartialAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null);
}
}
29 changes: 15 additions & 14 deletions src/Razor.Templating.Core/RazorTemplateEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,35 +58,36 @@ private static IRazorTemplateEngine CreateInstance()
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view data</param>
/// <returns></returns>
/// <returns>Rendered HTML string of the view</returns>
public async static Task<string> RenderAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null)
{
if (string.IsNullOrWhiteSpace(viewName))
{
throw new ArgumentNullException(nameof(viewName));
}

return await _instance.Value.RenderAsync(viewName, viewModel, viewBagOrViewData).ConfigureAwait(false);
}

/// <summary>
/// Renders the Razor View(.cshtml) Without Layout to String
/// </summary>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view bag or view data</param>
/// <returns>Rendered HTML string of the view</returns>
public async static Task<string> RenderPartialAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null)
{
return await _instance.Value.RenderPartialAsync(viewName, viewModel, viewBagOrViewData).ConfigureAwait(false);
}

/// <summary>
/// Renders View(.cshtml) To String
/// Renders the Razor View(.cshtml) To String
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view data</param>
/// <returns></returns>
/// <returns>Rendered HTML string of the view</returns>
[Obsolete("This method with generic type param is now obsolete and it will be removed in the upcoming versions. Please use the overload method without generic parameter instead.")]
public async static Task<string> RenderAsync<TModel>(string viewName, object viewModel, Dictionary<string, object> viewBagOrViewData)
{
// TODO: Remove this method in v2.0.0

if (string.IsNullOrWhiteSpace(viewName))
{
throw new ArgumentNullException(nameof(viewName));
}

return await _instance.Value.RenderAsync(viewName, viewModel, viewBagOrViewData).ConfigureAwait(false);
}
}
Expand Down
45 changes: 36 additions & 9 deletions src/Razor.Templating.Core/RazorTemplateEngineRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,56 @@ public RazorTemplateEngineRenderer(IServiceProvider serviceProvider)
}

/// <summary>
/// Renders View(.cshtml) To String
/// Renders the Razor View(.cshtml) To String
/// </summary>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Strongly typed object</param>
/// <param name="viewBagOrViewData">ViewData</param>
/// <returns></returns>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view bag or view data</param>
/// <returns>Rendered HTML string of the view</returns>
public async Task<string> RenderAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null)
{
if (string.IsNullOrWhiteSpace(viewName))
{
throw new ArgumentNullException(nameof(viewName));
}

var viewDataDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
var viewDataDictionary = GetViewDataDictionaryFromViewBagOrViewData(viewBagOrViewData);

foreach (var keyValuePair in viewBagOrViewData ?? new())
using var serviceScope = _serviceProvider.CreateScope();
var renderer = serviceScope.ServiceProvider.GetRequiredService<RazorViewToStringRenderer>();
return await renderer.RenderViewToStringAsync(viewName, viewModel, viewDataDictionary, isMainPage: true).ConfigureAwait(false);
}

/// <summary>
/// Renders the Razor View(.cshtml) Without Layout to String
/// </summary>
/// <param name="viewName">Relative path of the .cshtml view. Eg: /Views/YourView.cshtml or ~/Views/YourView.cshtml</param>
/// <param name="viewModel">Optional model data</param>
/// <param name="viewBagOrViewData">Optional view bag or view data</param>
/// <returns>Rendered HTML string of the view</returns>
public async Task<string> RenderPartialAsync(string viewName, object? viewModel = null, Dictionary<string, object>? viewBagOrViewData = null)
{
if (string.IsNullOrWhiteSpace(viewName))
{
viewDataDictionary.Add(keyValuePair!);
throw new ArgumentNullException(nameof(viewName));
}

var viewDataDictionary = GetViewDataDictionaryFromViewBagOrViewData(viewBagOrViewData);

using var serviceScope = _serviceProvider.CreateScope();
var renderer = serviceScope.ServiceProvider.GetRequiredService<RazorViewToStringRenderer>();
return await renderer.RenderViewToStringAsync(viewName, viewModel, viewDataDictionary).ConfigureAwait(false);
}
return await renderer.RenderViewToStringAsync(viewName, viewModel, viewDataDictionary, isMainPage: false).ConfigureAwait(false);
}

private static ViewDataDictionary GetViewDataDictionaryFromViewBagOrViewData(Dictionary<string, object>? viewBagOrViewData)
{
var viewDataDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());

foreach (var keyValuePair in viewBagOrViewData ?? new())
{
viewDataDictionary.Add(keyValuePair!);
}
return viewDataDictionary;
}
}
}
Loading

0 comments on commit 1255bf3

Please sign in to comment.