Let’s assume your Controller class has the following action method:
public ActionResult Index()
ViewData[“Message”] = “A text to display on the view.”;
When you add the code below to your Index.aspx View you will have the text displayed properly:
<%= ViewData[“Message”] %>
Output: A text to display on the view.
Without encoding this text, an alert will be displayed every time you want to display this text. Let’s check how to avoid it.
We are going to use one of two overloads of the static method Encode available under the Html class:
- string Encode(object value);
- string Encode(string value);
Basically most part of the time you need to display a text on a View you should encode it. The syntax is pretty straightforward.
On the Index.aspx View you will use the Encode method to encode the output:
<%= Html.Encode(ViewData[“Message”]) %>
Keep this in mind and apply it to your applications.
See you on the next tip!