Search code examples
c#asp.net-mvcooprazorasp.net-core-tag-helpers

Does Getter and Setter in ASP.MVC can instantiate an object?


From Microsoft MVC doc, related to Authoring Tag Helpers, I can read this:

using System;

namespace AuthoringTagHelpers.Models
{
    public class WebsiteContext
    {
        public Version Version { get; set; }
        public int CopyrightYear { get; set; }
        public bool Approved { get; set; }
        public int TagsToShow { get; set; }
    }
}

and this:

using System;
using AuthoringTagHelpers.Models;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AuthoringTagHelpers.TagHelpers
{
    public class WebsiteInformationTagHelper : TagHelper
    {
        public WebsiteContext Info { get; set; }

      public override void Process(TagHelperContext context, TagHelperOutput output)
      {
         output.TagName = "section";
         output.Content.SetHtmlContent(
             $@"<ul><li><strong>Version:</strong> {Info.Version}</li>
            <li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
            <li><strong>Approved:</strong> {Info.Approved}</li>
           <li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
         output.TagMode = TagMode.StartTagAndEndTag;
      }
   }
}

I never saw this kind of code before, where public WebsiteContext Info { get; set; } can automagically instantiate an object???

How it works? Is there any documentation on it?


Solution

  • The answer is in the document you linked:

    Note

    In the Razor markup shown below:

    <website-information info="new WebsiteContext {
                                    Version = new Version(1, 3),
                                    CopyrightYear = 1638,
                                    Approved = true,
                                    TagsToShow = 131 }" />
    

    Razor knows the info attribute is a class, not a string, and you want to write C# code. Any non-string tag helper attribute should be written without the @ character.

    The tag helper itself doesn't know how to instantiate the instance. You have to do it manually in the Razor markup or set it to a default value in the property declaration or class constructor in order for it to be non-null. Here is an example of setting the instance in the property declaration.

    public WebsiteContext { get; set; } = new WebSiteContext 
    { 
        Version = new Version(1, 3),
        CopyrightYear = 1638,
        Approved = true,
        TagsToShow = 131
    };