如何在ASP.MVC中指定多行编辑器的列和行?

75
在ASP.MVC 3中,如何为多行EditorFor(文本区域)指定列和行?我正在使用[UIHint("MultilineText")],但找不到任何关于如何添加文本区域属性的文档。
期望的HTML:
 <textarea cols="40" rows="10"></textarea>

我 MVC 3 模型的相关部分:

[UIHint("MultilineText")]
public string Description { get; set; }

我 Razor cshtml 文件的相关部分:

<div class="editor-field">
    @Html.EditorFor(model => model.Description)
</div>

我在查看源代码时得到的内容:

 <div class="editor-field">
     <textarea class="text-box multi-line" id="Description" name="Description"></textarea>
 </div>

如何设置行和列?

7个回答

148
使用 TextAreaFor。
@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })

或者为多行类使用样式。

您也可以为此编写EditorTemplate


对于阅读此内容的任何人:@cols@rows中的@是不必要的。即colsrows就足够了。 - Uwe Keim

30
在ASP.NET MVC 5中,您可以使用[DataType(DataType.MultilineText)]属性。它将呈现一个TextArea标记。
public class MyModel
{
    [DataType(DataType.MultilineText)]
    public string MyField { get; set; }
}

如果您需要指定行数,可以这样做:

@Html.EditorFor(model => model.MyField, new { htmlAttributes = new { rows = 10 } })

或者只需使用正确的重载TextAreaFor:

@Html.TextAreaFor(model => model.MyField, 10, 20, null)

很高兴知道他们做出了那个改变。 :-) - Dan Sorensen
自从MVC 3以来就一直存在:https://dev59.com/o2445IYBdhLWcg3wUYnM - Patrick McDonald
感谢您提供各种解决方案。它们对我很有帮助。 - Thomas.Benz

9

我相信这个也可以用更少的努力 (但我是在MVC 5中)

@Html.Description(model => model.Story, 20, 50, new { })

enter image description here


5

一种选择似乎是使用CSS来为文本区域添加样式

.multi-line { height:5em; width:5em; }

请参见此处SO的条目这个。 Amurra的答案似乎暗示在使用EditorFor时会自动添加此类,但您需要验证这一点。
编辑:已确认。所以,是的,如果您想使用EditorFor,则使用这种CSS样式就可以实现您想要的效果。
<textarea class="text-box multi-line" id="StoreSearchCriteria_Location" name="StoreSearchCriteria.Location">

感谢您回答原帖作者的问题。当使用创建输入字段的框架时,例如_Telerik ASP.NET MVC_,替换TextAreaFor不是一个选项。谢谢。 - Suncat2000

1
在MVC 5中。
              @Html.EditorFor(x => x.Address, 
              new {htmlAttributes = new {@class = "form-control", 
                   @placeholder = "Complete Address", @cols = 10, @rows = 10 } })

0

@Html.TextArea("txtNotes", "", 4, 0, new { @class = "k-textbox", style = "width: 100%; height: 100%;" })


0
在 .net VB 中,您可以通过以下方式在 Razor 文件中控制列和行:
@Html.EditorFor(Function(model) model.generalNotes, New With {.htmlAttributes = New With {.class = "someClassIfYouWant", .rows = 5,.cols=6}})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接