How can I create more than one editor template for a multi-line textbox in MVC3?

淺唱寂寞╮ 提交于 2019-11-29 04:09:05

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!