I am currently going through an MVC3 tutorial. Binding on an IEnumerable is done this way:
@ModelType IEnumerable(Of Product)
@foreach (var p in Model) {
<div class="item">
<h3>@p.Name</h3>
@p.Description
<h4>@p.Price.ToString("c")</h4>
</div>
}
Is this the only to do this? It smacks of the old Classic ASP way of doing things. [shiver]
I can’t really identify what bothers me about it, it could be just the pains of transitioning from WebForms where code-behind is the King.
Someone please assuage my fears.
It only smacks of it because you have code there.
Data binding did what in web forms? It gave you something to set in code behind that ‘magically’ worked in your presentation layer usually by black magic and calling back into various methods noted in the xml markup. You couldn’t track what was doing what when, you passed ‘object e’ as eventargs, etc. it was messy.
The above code is clean. Theres no calling back into code behind, and you don’t have to wait for a new version of a control to fix something for future browsers.
ASP mixed BUSINESS LOGIC into the presentation layer. Your above code is the presentation layer only, so your code is fine.
You could use WebGrid or Telerik’s grid (or MVCContrib) for better display and more ‘binding like’ stuff or you can use DisplayTemplates to customize this view so you can then just say Html.DisplayFor() wherever you use this object without having to repeat the above code.