Search code examples
asp.net-mvcasp.net-mvc-3delegateshtml-helpermvc-editor-templates

Why dose many MVC html Helpers uses Delegates as input parameters


In MVC if you want to create an editor for a property or a display for you property you do something like that:

@Html.EditorFor(m=> m.MyModelsProperty);
@Html.DisplayFor(m=> m.MyModlesProperty);

Why do we have to pass a delegate why can't we just pass the model's property directlly? e.g.:

@html.EditorFor(Model.MyModlesProperty);

Solution

  • The reason for this is because of Metadata. You know, all the attributes you could put on your model, like [Required], [DisplayName], [DisplayFormat], ... All those attributes are extracted from the lambda expression. If you just passed a value then the helper wouldn't have been able to extract any metadata from it. It's just a dummy value.

    The lambda expression allows to analyze the property on your model and read the metadata from it. Then the helper gets intelligent and based on the properties you have specified will act differently.

    So by using a lambda expression the helper is able to do a lot more things than just displaying some value. It is able to format this value, it is able to validate this value, ...