Html.Display and Html.DisplayFor in MVC Framework

March 13, 2018 0 Comments A+ a-

ASP .Net

Html.Display and Html.DisplayFor

You learn on this topic for How can you create string literal in MVC Framework by using HTMLHelper methods.
HTMLHelper class provide two extension methods for generate hidden field.
  • Html.Display()
  • Html.DisplayFor()

Html.Display()

  • Html.Display() is loosely typed method. So It always require property name as string.
  • It generates a string value based on the value of the model property
  • It doesn't get error at compile time.
It have so many overloaded methods such as
  • Display(String)
  • Display(String, Object)
  • Display(String, String)
  • Display(String, String, Object)
  • Display(String, String, String)
  • Display(String, String, String, Object)
Known more details on the Display, Please click it here.

Html.DisplayFor()

  • Html.DisplayFor() also used for the password field in view for the model object property specified using a lambda expression.
  • It generates a string value based on the value of the model property
  • This method is a strongly typed extension method.
  • It gets error at compile time, if you assign wrong property name.
It have so many overloaded methods such as
  • DisplayFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>)
  • DisplayFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, Object)
  • DisplayFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, String)
  • DisplayFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, String, Object)
Known more details on the DisplayFor, Please click it here.
We will discuss this on the below example.
EmployeeModel.cs
   
  public class EmployeeModel
        {
        public int Id { set; get; }
        public string Name { set;get; }
        public string Location { set; get; }
        }

EmployeeController.cs
   
  public class EmployeeController : Controller
    {
         public ActionResult Create ( )
            {
            EmployeeModel empmodel = new EmployeeModel() { Id = 1, Name = "Rio", Location = "Bangalore" };
            return View(empmodel);
            }
    }

Create.cshtml
   
@model MVCIntro1.Models.EmployeeModel
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Create

@using (Html.BeginForm()) {

Display

@Html.Display("Name")

DisplayFor

@Html.DisplayFor(Model => Model.Name) }
We have successfully completed our code part. Let's run the application and see the appropriate HTML output
HTML Output:
   

Display

Rio

DisplayFor

Rio