Is it possible to load ViewContext outside of a view?

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật