Question:
- Could you explain why
@Html.DisplayFor(x=>x)
yields the same result as@Html.DisplayForModel()
in the following scenario? - 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>