Learn Html.Display and Html.DisplayFor Helper Method in ASP.NET MVC5 with Example

In this chapter, you will learn:
  1. What is Html.Display and Html.DisplayFor
  2. How to define Html.Display Helper Method
  3. How to Bind Html.DisplayFor to a Model
  4. How to Display Textbox string into Html.Display Method
  5. Programming Example of Html.DisplayFor

What is Html.Display and Html.DisplayFor Method?

Html.Display and Html.DisplayFor both are used to print string value to the screen. However, you can also use plain HTML tag for displaying text on the screen but Html.Display Extension Method provides more formatting option. Html.Display is loosely typed method whereas Html.DisplayFor is strongly typed method.

Programming Example

Model: UserModel.cs

namespace HtmlHelperDemo.Models
{
    public class UserModel
    {
        public string UserName { get; set; }        
    }
}

View: Index.cshtml

@using HtmlHelperDemo.Models
@model UserModel

<h1>Html.DisplayFor Example</h1>

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <span>Enter Your Name:</span>
    @Html.TextBoxFor(m => m.UserName)
    <input id = "Submit" type = "submit" value = "submit" />
       
}

<hr />

<strong>Strongly Typed Value:</strong> @Html.DisplayFor(m => m.UserName)<br />

<strong>Loosely &nbsp;Typed Value: </strong> @Html.Display("UserName")

Controller: HomeController.cs

using System.Web.Mvc;
using HtmlHelperDemo.Models;

namespace HtmlHelperDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {            
             return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc, UserModel um)
        {
            if (ModelState.IsValid)
            {
                um.UserName = fc["UserName"];
                return View(um);
            }
            else
            {
                return View();
            }
        }
    }
}

Output
Html.Display Example
 

Share your thought