Could you explain why @Html.DisplayFor(x=>x) yield

2019-06-04 18:37发布

问题:

Question:

  1. Could you explain why @Html.DisplayFor(x=>x) yields the same result as @Html.DisplayForModel() in the following scenario?
  2. When do they produce different result?

Model

using System.Collections.Generic;

namespace MvcMusicStore.Models
{
    public class Genre
    {
        public int GenreId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Album> Albums { get; set; }
    }
}

Controller

using System.Linq;
using System.Web.Mvc;
using MvcMusicStore.Models;

namespace MvcMusicStore.Controllers
{
    public class HomeController : Controller
    {
        MusicStoreEntities db = new MusicStoreEntities();
        //
        // GET: /Home/

        public ActionResult Index()
        {
            var genres = db.Genres.ToList();
            return View(genres);
        }
     }
}

Index.cshtml View

@model IEnumerable<MvcMusicStore.Models.Genre>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.DisplayFor(x=>x)

or

@model IEnumerable<MvcMusicStore.Models.Genre>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@Html.DisplayForModel()

Shared/DisplayTemplates/Genre.cshtml

@model MvcMusicStore.Models.Genre

<fieldset>
    <legend>Genre</legend>

    <div class="display-label">Name</div>
    <div class="display-field">@Model.Name</div>

    <div class="display-label">Description</div>
    <div class="display-field">@Model.Description</div>
</fieldset>

回答1:

The DisplayForModel() method returns HTML markup for each property in the model.

The DisplayFor() method returns HTML markup for each property in the object that is represented by the Lambda Expression you provide.

So when you say DisplayFor(x => x), your expression says, "use the entire model," which gives you the same result as DisplayForModel().

A demonstration Visual Studio project illustrating DisplayFor() is available here.