How can I create more than one editor template for

2019-01-24 07:52发布

I have the following two types of multiline textareas in my views:

<textarea cols="100" rows="15" class="full-width" id="dialogText" 
          name="Text">@Model.Text</textarea>

<textarea cols="100" rows="10" class="full-width" id="dialogText" 
          name="Text">@Model.Text</textarea> 

I would like to take advantage of custom editor templates, but keep the ability to specify attributes differently (e.g. the rows are different between the two above).

Is it possible for me to declare and use two different kinds of templates for the same field? If so then how should I declare the template and how do I specify the different templates to use?

Also how can I declare the different cols and rows. Can I use cols,rows or should I specify height and width in CSS such as width=500px, height=600px or 400px?

2条回答
女痞
2楼-- · 2019-01-24 08:35

You could override the default editor template (~/Views/Shared/EditorTemplates/MultilineText.cshtml):

@Html.TextArea(
    "", 
    ViewData.TemplateInfo.FormattedModelValue.ToString(),
    ViewData
)

and then assuming you have defined a view model:

public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

inside the main view you could do this:

@model MyViewModel

@Html.EditorFor(x => x.Text, new { cols = "100", rows = "15", id = "dialogText", @class = "full-width" })
@Html.EditorFor(x => x.Text, new { cols = "100", rows = "10", id = "dialogText", @class = "full-width" })

which will render the expected output:

<textarea class="full-width" cols="100" id="dialogText" name="Text" rows="15">
    hello world
</textarea>

<textarea class="full-width" cols="100" id="dialogText" name="Text" rows="10">
    hello world
</textarea>

Also you could enhance the editor template so that you don't need to specify the @class attribute at every EditorFor call like this:

@{
    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "full-width";

}
@Html.TextArea(
    "", 
    ViewData.TemplateInfo.FormattedModelValue.ToString(),
    htmlAttributes
) 

and now you could:

@model MyViewModel
@Html.EditorFor(x => x.Text, new { cols = "100", rows = "15", id = "dialogText" })
@Html.EditorFor(x => x.Text, new { cols = "100", rows = "10", id = "dialogText" })

Oh and don't forget that ids must be unique in HTML so this id = "dialogText" should obviously be different for the second textarea.

查看更多
Fickle 薄情
3楼-- · 2019-01-24 08:46

you can create an editor template MultiLine1.cshtml and MultiLine2.cshtml and in your view model you can use UIHint to specify which editor template you want to use for that particular property. But you can specify only one template for one property. On different properties of same type, you can use different templates though.

查看更多
登录 后发表回答