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.
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.
@model Student
@Html.DisplayFor(m => m.StudentName)
"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
@Html.Display("StudentName")
"Steve"