Can I use more than one editor template for the same class in MVC3?

I have a class:

public class Book { public int BookId { get; set; } public string BookName { get; set; } public string Description { get; set; } } 

and editor template:

 @model MySimpleEditorTemplate.Models.Book @Html.DisplayFor(p => p.BookId) @Html.EditorFor(p => p.BookId) @Html.DisplayFor(p => p.BookName) @Html.EditorFor(p => p.BookName) @Html.DisplayFor(p => p.Description) @Html.EditorFor(p => p.Description) 

I can use the editor template as follows:

 @Html.EditorFor(model => model.Book) 

However, what if I want to have two editor templates or two display templates and use them for the same class? Is it possible?

+4
source share
2 answers

Yes

 public static MvcHtmlString EditorFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName ) 

http://msdn.microsoft.com/en-us/library/ff406506.aspx

"If the template template whose name matches the templateName parameter is in the Controller EditorTemplates folder, this template is used to render the expression. If the template is not found in the Controller EditorTemplates folder, the Views \ Shared \ EditorTemplates folder look for the template that matches the templateName parameter name. If template not found, default template is used. "

+4
source

YES, you can have a "default" one with its name Book.cshtml ... and this one starts every time you use EditorFor .

You may have a different editor template for the book, letโ€™s name it BookTheOtherWay.cshtml and there you will place your โ€œother editorโ€. Now when using EditorFor you just need to pass the template name as another parameter in the EditorFor template.

 @Html.EditorFor(model => model.MyBook, "BookTheOtherWay" ) 

This works the same for DisplayTemplates and the DisplayFor helper.

 @Html.DisplayFor(model => model.MyBook, "BookTheOtherWay" ) 
+13
source

Source: https://habr.com/ru/post/1382005/


All Articles