asp.net-mvc - 如何在MVC3中为多行文本框创建多个编辑器模板?

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 razor

我的 View 中有以下两种类型的多行文本区域:

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

我想利用自定义编辑器模板的优势,但保持以不同的方式指定属性的能力(例如,上述两个之间的rows不同)。

我可以为同一字段声明和使用两种不同的模板吗?如果是这样,那么我应该如何声明模板以及如何指定要使用的其他模板?

另外,我如何声明不同的列和行。我可以使用cols,rows还是应该在CSS中指定高度和宽度,例如width=500px, height=600px400px

最佳答案

您可以覆盖default editor template(~/Views/Shared/EditorTemplates/MultilineText.cshtml):

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

然后假设您已定义 View 模型:
public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

在主 View 中,您可以执行以下操作:
@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" })

这将呈现预期的输出:
<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>

另外,您可以增强编辑器模板,这样就无需在每个EditorFor调用中都指定@class属性,如下所示:
@{
    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "full-width";

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

现在您可以:
@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" })

哦,别忘了id在HTML中必须是唯一的,因此,第二个textarea的id = "dialogText"应该明显不同。

关于asp.net-mvc - 如何在MVC3中为多行文本框创建多个编辑器模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10695983/

相关文章:

c# - 在 ASP.MVC 参数中使用破折号 (-)

asp.net-mvc - 有和没有 pageBaseType 的页面配置部分有什么区别

c# - 如何根据 ASP.NET MVC 中的 Controller 操作在页面 javascript 中设置变量?

c# - 带 Moq 的 MV3 测试项目,使用特定表达式时如何返回对象?

c# - ASP.NET MVC3 C#-foreach

c# - MVC 查看替代内容

C# 6.0 功能不适用于 Visual Studio 2015

javascript - 如何从 Html.ActionLink 转换为链接到 Ajax 调用的按钮?

jquery 客户端验证在 MVC3 部分 View 中不起作用

asp.net - 编辑并继续在 VS 2010/ASP.Net MVC 2 中不起作用