开发者

Could you explain why @Html.DisplayFor(x=>x) yields the same result as @Html.DisplayForModel()?

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<MvcMu开发者_StackOverflow社区sicStore.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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜