Search code examples
c#asp.net-corerazorrazor-pages

How i can set section from code in Razor pages?


So, I know that I can render section with @RenderSection("MySection") and set his value with

@section MySection{
   <p>Some Html</p>
}

But how i can set section value from my model? Something like:

public void OnGet(){
   Model.SetSection("MySection", "<p>Some html</p>");
}

Solution

  • Sections in Razor views are typically defined directly within the view and are not set directly from the ViewModel. However, you can achieve similar results by setting a ViewModel property that holds the content you want to include within a section, and then rendering that content in the view using @Html.Raw, AspNetCore.Html or other appropriate techniques. Let's me share two techniques with you:

    1. Using AspNetCore.Html With this technique you strigify the Html content befor sent to view.
    • Razor ViewModel class

        using Microsoft.AspNetCore.Html;
      
        public class YourModel : PageModel
        {
            public HtmlString DynamicContent { get; private set; }
      
            public void OnGet()
            {
                string htmlContent = "<p>Some Html</p>";
      
                DynamicContent = new HtmlString(htmlContent);
            }
        }
      
    • Razor View

         @model YourModel
         @section DynamicSection {
            @(Model.DynamicContent)
         }
        
    • In the _Layout

      @await RenderSectionAsync("DynamicSection", required: false)
      



    2. Using @Html.Raw

    • In Razor ViewModel

        public class YourModel : PageModel
        {
            public string DynamicContent { get; private set; }
      
            public void OnGet()
            {
                DynamicContent = "<p>Some Html</p>";
            }
        }
      
    • In Razor View

         @model YourModel
         @section DynamicSection {
            @Html.Raw(Model.DynamicContent)
         }
        
    • In the _Layout

      @await RenderSectionAsync("DynamicSection", required: false)