creating multiline textbox using Html.Helper function
C#asp.netasp.net MvcC# Problem Overview
I am trying to create a multiline Textbox using ASP.NET MVC with the following code.
<%= Html.TextBox("Body", null, new { TextBoxMode = "MultiLine", Columns = "55px", Rows = "10px" })%>
It just shows up a single line fixed sized textbox.
on the other hand
<asp:TextBox runat="server" ID="Body" TextMode="MultiLine" Columns="55" Rows="10"></asp:TextBox>
renders the right view, but in the controller's post method with formCollection named form
form["Body"];
returns a null value.
C# Solutions
Solution 1 - C#
A multiline textbox in html is <textarea>
:
<%= Html.TextArea("Body", null, new { cols = "55", rows = "10" }) %>
or:
<%= Html.TextArea("Body", null, 10, 55, null) %>
or even better:
<%= Html.TextAreaFor(x => x.Body, 10, 55, null) %>
And yet another possibility is to decorate your view model property with the [DataType]
attribute:
[DataType(DataType.MultilineText)]
public string Body { get; set; }
and in your view:
<%= Html.EditorFor(x => x.Body) %>
and set the width and height through CSS.
Solution 2 - C#
MVC4 you should use:
@Html.TextAreaFor(x => x.Body, 10, 15, null)
Solution 3 - C#
This allows to multi-line, set custom width and height and setting place holder. For validation used StringLength or RegularExpression in Model.cs
Razor View Syntax
@Html.TextAreaFor(model => model.property, new { style = "width: 420px; height: 100px;", placeholder = "Placeholder here.." })
Solution 4 - C#
I think the Html.EditorFor Is what you're looking for. That's only for MVC2 and up though. Does that help?
If you're using DataAnnotations and decorate your property with the [DataType(DataType.MultilineText)]
Attribute, MVC should scaffold out the required html for you.
Solution 5 - C#
In Entity layer:
[MaxLength(500)]
public string Body { get; set; }
And in view:
@Html.TextAreaFor(model => model.Body, new { rows = 10, cols = 50 })
Solution 6 - C#
VB.net solution:
@Html.TextAreaFor(Function(Model) Model.Body, 3, 55, Nothing)