Can I use more than one editor template for the sa

2019-04-10 07:21发布

问题:

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?

回答1:

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."



回答2:

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" )