Is it possible to get ViewContext outside of a view?
I have a class which I include in ViewImports, but I get an error when I try to load ViewContext (ViewContext is null).
Or do I have to implement it in a tag helper?
ViewUtility:
public sealed class ViewUtility : IViewUtility
{
private readonly IHtmlHelper _htmlHelper;
public ViewUtility(IHtmlHelper htmlHelper)
{
_htmlHelper = htmlHelper;
(this.HtmlHelper as IViewContextAware).Contextualize(this.ViewContext);
}
[ViewContext]
public ViewContext ViewContext { get; set; }
public ViewDataDictionary ViewData => this.ViewContext.ViewData;
public IHtmlHelper HtmlHelper => _htmlHelper;
}
ViewImports:
@using SL.Assets.Core.Components.Utility;
@inject IViewUtility ViewUtility
5
As an answer to the question:
Is it possible to load “ViewContext” outside of a view?
we can briefly say:
Yes, it is possible using the “MVC ViewEngine”, as I will explain below, but in my opinion, this may be Anti-Pattern.
In “MVC”, one of the goals is to separate the model and the view. It is logical to use the model in the view, but if you mean to use the information of the view inside the model, it may destroy the “MVC” structure to some extent.
On the other hand, considering that “ViewContext” depends on the information of the controller, the view name and the model object, it will actually be parametric. So if we want, for example, to have a service that can extract the “ViewContext” anywhere without any additional parameters, it is probably not possible.
Actually it is good to use “ViewContext” in “cshtml” files.
In any case, according to this Stack Overflow question, for example if we want to have a “ViewContext” in the controller. We can add the following code to the project. For example, an “ASP .NET Core Web App (Model-View-Controller)” project in “.NET 6” for “Visual Studio 2022”.
ControllerExtensions:
public static class ControllerExtensions
{
public static ViewContext? GetViewContext<TModel>(this Controller controller, string viewName, TModel model, bool isPartial = false)
{
if (!string.IsNullOrEmpty(viewName))
{
controller.ViewData.Model = model;
using var writer = new StringWriter();
var viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
var isMainPage = !isPartial;
var viewResult = viewEngine?.FindView(controller.ControllerContext, viewName, isMainPage);
if (viewResult?.Success == true)
{
ViewContext viewContext = new(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
controller.TempData,
writer,
new HtmlHelperOptions()
);
return viewContext;
}
}
return null;
}
}
Sample action method in controller class:
public IActionResult SomeActionMethod()
{
var TestModelData = new { };
var viewContextForIndexPage = this.GetViewContext("Index", TestModelData);
return View();
}
1
Here is the detailed steps for you, it can fix the ViewContext null issue.
IViewUtility.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace MyMvcProject.Models
{
public interface IViewUtility
{
ViewContext ViewContext { get; set; }
ViewDataDictionary ViewData { get; }
string RenderMessage(ViewContext viewContext);
}
}
ViewUtility.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace MyMvcProject.Models
{
public sealed class ViewUtility : IViewUtility
{
public ViewUtility()
{
}
[ViewContext]
public ViewContext ViewContext { get; set; }
public ViewDataDictionary ViewData => this.ViewContext.ViewData;
// Not using IHtmlHelper here, so comment it
//public IHtmlHelper HtmlHelper => _htmlHelper;
// For testing
public string RenderMessage(ViewContext viewContext)
{
if (viewContext != null && viewContext.View != null)
{
return $"View Name: {viewContext.View.Path}";
}
return "ViewContext is not available.";
}
}
}
_ViewImports.cshtml
@using MyMvcProject
@using MyMvcProject.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject MyMvcProject.Models.IViewUtility ViewUtility
Program.cs
using MyMvcProject.Models;
var builder = WebApplication.CreateBuilder(args);
// Register it
builder.Services.AddScoped<IViewUtility,ViewUtility>();
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Home/Index.cshtml
@model dynamic
@inject MyMvcProject.Models.IViewUtility ViewUtility
@{
ViewData["Title"] = "Home Page";
}
<div>
<h1>Welcome to the Home Page!</h1>
<p>@ViewUtility.RenderMessage(ViewContext)</p>
</div>
Test Result
7