{"id":119,"date":"2014-04-15T07:00:29","date_gmt":"2014-04-15T11:00:29","guid":{"rendered":"https:\/\/cindypotvin.com\/?p=119"},"modified":"2021-08-01T19:58:59","modified_gmt":"2021-08-01T23:58:59","slug":"character-encodings-with-razor-helpers","status":"publish","type":"post","link":"https:\/\/cindypotvin.com\/character-encodings-with-razor-helpers\/","title":{"rendered":"Character encoding with ASP.NET MVC helpers"},"content":{"rendered":"

In ASP.NET MVC, one of the ways to reuse parts of a web application template is to use helpers. There are two kind of helpers that can be used with Razor templates: helpers created directly from Razor templates using the @helper directive and helpers created from a C# class. To declare a helper with the @helper directive in a Razor view or in a .cshtml file in the App_code folder, you have to use the following syntax :<\/p>\n\n\n

\n@helper PageHeader(string pageTitle)\n   {\n   <h1>@pageTitle<\/h1>\n   }\n<\/pre>\n\n\n\n

Helpers created with the @helper directive always return a System.Web.WebPages.HelperResult<\/em> that implements the System.Web.IHtmlString<\/em> interface. This interface tells the Razor engine that the string returned is HTML-encoded and does not need to be encoded again to be safe. By default, all strings are encoded by the Razor engine, which means that characters not allowed in URLs or inside HTML tags are encoded into their character-entity equivalents : for example < and > becomes %3c and %3e.<\/p>\n\n\n\n

But if you want to create your own helpers in a C# class, the return type to use is not that clear. The HelperResult<\/em> class should not be used since it belongs the System.Web.WebPages<\/em> namespace specific to the Razor syntax functionalities and not to the System.Web.Mvc<\/em> namespace containing the ASP.NET MVC framework functionalities. The documentation of the HelperResult<\/em> class also clearly indicates that it is not intended to be used directly from your own code. That leaves us with two options :<\/p>\n\n\n\n