2

I am following an ASP.net MVC 3 tutorial , which sets up an online music store .

This code is the Delete.cshtml view for StoreManagerController.cs

@model MyStore.Models.Album

@{ ViewBag.Title = "Delete";}

<h2>Delete</h2>    
<h3>Are you sure you want to delete this?</h3>
@Html.DisplayFor(model => model.Genre.Name)

What I'd like to know is , in the last line, why cant we do this

@Html.DisplayFor(model.Genre.Name)

Why is a lambda expression used here? Thanks

iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

1 Answers1

0

If model.Genre.Name were null, what type of display would be rendered for it?

Since display templates are chosen based on the declared type of the model, the system needs to know what the declared type is, because a null value would have no type at runtime.

You can also decorate your model's properties with attributes to change the way that they are displayed. The system wouldn't know what attributes are on that property if it were only given a value.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • what if it really is null.... how does the lambda expression fix it? I mean, if it is null then we don't get an exception? how does lambda expression save the day? – iAteABug_And_iLiked_it May 17 '13 at 15:24
  • 1
    @iAteABug_And_iLiked_it: Because we're using a lambda expression, MVC can analyze the properties that are being accessed by that expression and select and set up the display template based purely on reflection. Then, if the value does evaluate to null, MVC just passes a null model value to that display template. – StriplingWarrior May 17 '13 at 22:54