【问题标题】:creating multiline textbox using Html.Helper function使用 Html.Helper 函数创建多行文本框
【发布时间】:2011-02-16 20:50:35
【问题描述】:

我正在尝试使用带有以下代码的 ASP.NET MVC 创建一个多行文本框。

<%= Html.TextBox("Body", null, new { TextBoxMode = "MultiLine", Columns = "55px", Rows = "10px" })%>

它只显示一个固定大小的单行文本框。

另一方面

<asp:TextBox runat="server" ID="Body" TextMode="MultiLine" Columns="55" Rows="10"></asp:TextBox> 

渲染正确的视图,但在控制器的 post 方法中使用名为 form 的 formCollection

form["Body"]; 

返回一个空值。

【问题讨论】:

  • 刚刚注意到在您的第一个示例中,您有 Columns = "55px"。这是错字还是代码中的那样?看看把它拿出来是否能解决你的问题:)我不确定它是否会,所以这就是为什么这只是一个评论......
  • 除非这是一个 MVC1 项目,否则我仍然会走数据注释路线

标签: c# asp.net asp.net-mvc


【解决方案1】:

html中的多行文本框是&lt;textarea&gt;:

<%= Html.TextArea("Body", null, new { cols = "55", rows = "10" }) %>

或:

<%= Html.TextArea("Body", null, 10, 55, null) %>

甚至更好:

<%= Html.TextAreaFor(x => x.Body, 10, 55, null) %>

还有一种可能性是使用[DataType] 属性来装饰您的视图模型属性:

[DataType(DataType.MultilineText)]
public string Body { get; set; }

在你看来:

<%= Html.EditorFor(x => x.Body) %>

并通过 CSS 设置宽度和高度。

【讨论】:

  • 我通常使用EditorFor,并用Css设置高度等。看起来更干净
  • 非常感谢,这行得通!我也刚刚发现列的属性是 cols...
  • @Html.TextAreaFor(model => model.Comments, 5, 2, null) 适用于行,但列似乎被忽略?
  • dataType 属性太棒了!
  • 类如new { @class = "form-control" }检查here
【解决方案2】:

你应该使用 MVC4:

@Html.TextAreaFor(x => x.Body, 10, 15, null)

【讨论】:

  • 类如new { @class = "form-control" }检查here
【解决方案3】:

这允许多行,设置自定义宽度和高度以及设置占位符。 在 Model.cs 中使用 StringLength 或 RegularExpression 进行验证

Razor 视图语法

@Html.TextAreaFor(model => model.property, new { style = "width: 420px; height: 100px;", placeholder = "Placeholder here.." })

【讨论】:

    【解决方案4】:

    我认为Html.EditorFor 是您正在寻找的。不过,这仅适用于 MVC2 及更高版本。这有帮助吗?

    如果您使用 DataAnnotations 并使用 [DataType(DataType.MultilineText)] 装饰您的财产 属性,MVC应该为你搭建出需要的html。

    【讨论】:

    • 没有MultilineText 属性。你的意思是DataType 属性吗?
    【解决方案5】:

    在实体层:

    [MaxLength(500)]
    public string Body { get; set; }
    

    并且在视图中:

    @Html.TextAreaFor(model => model.Body, new { rows = 10, cols = 50 })
    

    【讨论】:

      【解决方案6】:

      VB.net 解决方案:

      @Html.TextAreaFor(Function(Model) Model.Body, 3, 55, Nothing)

      【讨论】:

        猜你喜欢
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        相关资源
        最近更新 更多