HtmlHelper - Display HTML String

Learn how to create html string literal using the HtmlHelper class in razor view.

The HtmlHelper class includes two extension methods to generate html string : Display() and DisplayFor().

We will use the following model class with the Display() and DisplayFor() method.

Example: Student Model
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}

Html.DisplayFor()

The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.

DisplayFor() method Signature: MvcHtmlString DisplayFor(<Expression<Func<TModel,TValue>> expression)

Visit MSDN to know all the overloads of DisplayFor() method.

Example: DisplayFor() in Razor View
@model Student

@Html.DisplayFor(m => m.StudentName)
Html Result:
"Steve"

In the above example, we have specified StudentName property of Student model using lambda expression in the DisplayFor() method. So, it generates a html string with the StudentName value, Steve, in the above example.

Display()

The Html.Display() is a loosely typed method which generates a string in razor view for the specified property of model.

Display() method Signature: MvcHtmlString Display(string expression)

Visit docs.microsoft.com to know all the overloads of Display() method

Example: Html.Display() in Razor View
@Html.Display("StudentName")
Html Result:
"Steve"
Want to check how much you know ASP.NET MVC?