Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have for example a class:

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

and an 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 like this:

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

However what if I want to have two editor templates or two display templates and use one or other for the same class? Is this possible?

like image 359
Samantha J T Star Avatar asked Nov 19 '11 02:11

Samantha J T Star


2 Answers

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

You can have another editor template for Book, let's say calling it BookTheOtherWay.cshtml and there you place your "other editor view". Now, when using EditorFor, you just need to pass the template name as other parameter in the EditorFor template.

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

This works the same way for DisplayTemplates and the DisplayFor helper.

@Html.DisplayFor(model => model.MyBook, "BookTheOtherWay" )
like image 188
Romias Avatar answered Oct 17 '22 05:10

Romias


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 a template whose name matches the templateName parameter is found in the controller's EditorTemplates folder, that template is used to render the expression. If a template is not found in the controller's EditorTemplates folder, the Views\Shared\EditorTemplates folder is searched for a template that matches the name of the templateName parameter. If no template is found, the default template is used."

like image 26
LostInComputer Avatar answered Oct 17 '22 05:10

LostInComputer