Search code examples
asp.net-mvc.net-corehtml-helper

How do I create something similar to the HTMLHelper namespace for the business name?


I would like to create something that can be called into any view in a website like this

@MyBusinessName.TelephoneNumber
@MyBusinessName.Address
etc...

In the same way I would call a HtmlHelper

@Html.ActionLink()

How do I add a namespace like "MyBusinessName" for use in an MVC view?


Solution

  • Html in Razor pages is a property of the class that pages inherit from, so of course you can't implement what you want in the same way as the standard HTML helper works. But I can suggest a different solution.

    You may define a static class in your project that will work as your own helper (define there static methods/properties you want to use in views). I'd suggest something like the following:

    using System.Web.Mvc;
    
    namespace YourProject.Infrastructure {
      public static class YourBusinessHelper {
        public static MvcHtmlString TextBox(string name) {
          string html = string.Format("<input name=\"{0}\" />", name);
          return new MvcHtmlString(html);
        }
    
        // ...
      }
    }
    

    System.Web.Mvc.MvcHtmlString is a class representing HTML markup that an HTML helper method inserts into the view where it is used. You may create it using a constructor that receives a string parameter containing the needed HTML markup — like in my code.

    Now you can use this class in your views. You just need to import the containing namespace with this Razor instruction:

    @using YourProject.Infrastructure
    

    I'd suggest to put it into the view start file (_ViewStart.cshtml) so that it applies to all your views.

    The sample helper method above can be used simply:

    @YourBusinessHelper.TextBox("TextBoxName")
    

    UPDATE: you may also create an extension method for HtmlHelper:

    using System.Web.Mvc;
    
    namespace YourProject.Infrastructure {
      public static class YourBusinessHelper {
        public static string CompanyPhoneNumber(this HtmlHelper helper) {
          return "+82649256720";
        }
    
        // ...
      }
    }
    

    You may use string not MvcHtmlString in helper methods if they return plain text (no HTML markup).

    Use it like a built-in helper method:

    @:Call us: @Html.CompanyPhoneNumber()