c# - Understanding list of objects based View syntax ASP.NET MVC -
hi created view using visual studio template should display list of objects. here syntax visual studio generated:
@model ienumerable<testmvcapplication.models.product> @{ viewbag.title = "index"; } <h2>index</h2> <p> @html.actionlink("create new", "create") </p> <table> <tr> <th> @html.displaynamefor(model => model.name) </th> <th> @html.displaynamefor(model => model.available) </th> <th> @html.displaynamefor(model => model.price) </th> <th></th> </tr> @foreach (var item in model) { <tr> <td> @html.displayfor(modelitem => item.name) </td> <td> @html.displayfor(modelitem => item.available) </td> <td> @html.displayfor(modelitem => item.price) </td> <td> @html.actionlink("edit", "edit", new { id=item.id }) | @html.actionlink("details", "details", new { id=item.id }) | @html.actionlink("delete", "delete", new { id=item.id }) </td> </tr> } </table>
i confused above syntax. particularly:
1) first time see above:
@html.displaynamefor(model => model.name)
i know refer model should use model
(with capital m). why above used small m
? model
(with small m) mean above? how ide know model.name
exists (with small m).
if model.name
used mean ienumerable
has property name
(right?) not case right? explanation dummies appreciated. model
(with small m)?
2) this:
@html.displayfor(modelitem => item.name)
is confusing. modelitem
- not declared anywhere? how come appeared here? how works? not more logical have item=> item.name
?
i don't have hands on mvc can clarify 2nd question.
@html.displayfor(modelitem => item.price)
well has got nothing mvc, if (really) know lambda expression , anonymous functions. here modelitem parameter , item.price return value. imagine translating to:
typeofpriceprop anonymousfunction(sometype modelitem) { return item.price; }
now function not work if called directly because not know item. however, lambda expressions make possible because can refer variables outer scope well. outer scope here @foreach (var item in model)
defines item.
in short, can in @html.displayfor(modelitem => item.price)
modelitem parameter not used @ (also not need declared. lambda). in fact, if changed item.price modelitem.price, not work.
Comments
Post a Comment