0

just read the article for how to work with template for re-usability from this url http://www.iminfo.in/post/mvc-multiple-checkboxes-select-in-html-table-bootstrap

this article show just we need to create a template file in editor template folder with viewmodel name.

enter image description here

i just like to know how MVC @Html.EditorFor can point or pickup to right template file. need some guide line like how MVC resolve right template to pick up. thanks

Mou
  • 15,673
  • 43
  • 156
  • 275

2 Answers2

3

By default templates are resolved by data type so if you use

@Html.EditorFor(model => model.ProductViewModel)it will use EditorTemplates/ProductViewModel.cshtml template.

However if you need to use a different template you can use an override of @Html.EditorFor(model => model.ProductViewModel, "yourTemplateName") that accepts template name.

Additional option is to set a template by using UIHint attribute on the property for example:

public class ComplexModel
{
    //will search for EditorTemplates/SomeProductModelTemplate.cshtml
    [UIHint("SomeProductModelTemplate")]
    public ProductViewModel ProductModel {get;set;}
}
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • can u redirect me to bit details discussion for this syntax `@Html.EditorFor(model => model.ProductViewModel, "yourTemplateName")` and `[UIHint("SomeProductModelTemplate")]` – Mou Oct 11 '15 at 14:38
  • UIHint attribute: http://stackoverflow.com/questions/8196372/what-is-use-of-uihint-attribute-in-mvc – Alex Art. Oct 11 '15 at 14:47
  • EditorFor template: https://msdn.microsoft.com/en-us/library/ee407414(v=vs.118).aspx – Alex Art. Oct 11 '15 at 14:47
1

The template is resolved by data type. In your example you have editor templates folder with a ProductViewModel template. If you then create a view under the home directory using the EditorFor method with a ProductViewModel type then MVC will resolve the custom editor template. Similarly, if you created a DateTime.cshtml file under editor templates then that would be used for EditorFor method calls with a DateTime parameter.

@Html.EditorFor(model => model.ProductViewModelItem) //will use the custom template
@Html.EditorFor(model => model.StringItem) //will not use the custom template

You can also do the same with DisplayTemplates for DisplayFor or any of the other Html "for" helpers.

James Santiago
  • 2,883
  • 4
  • 22
  • 29