53

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496
paaone
  • 569
  • 1
  • 5
  • 11
  • Just noticed that on your first example, you have Columns = "55px". Is that a typo or it's like that in the code? See if taking that out fixes your problem :) I am not sure if it will so that's why this is just a comment... – Dmitriy Khaykin Feb 16 '11 at 21:04
  • I would still go down the dataannotations route, unless this is an MVC1 project – MrBliz Feb 16 '11 at 21:07

6 Answers6

107

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
6

MVC4 you should use:

@Html.TextAreaFor(x => x.Body, 10, 15, null)
ahaliav fox
  • 2,217
  • 22
  • 21
  • with class like `new { @class = "form-control" }` check [here](http://stackoverflow.com/a/6218024/2218697) – Shaiju T Nov 10 '15 at 14:15
3

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.." })
Atish Kumar Dipongkor
  • 10,220
  • 9
  • 49
  • 77
Shimax s
  • 51
  • 4
0

In Entity layer:

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

And in view:

@Html.TextAreaFor(model => model.Body, new { rows = 10, cols = 50 })
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
0

VB.net solution:

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

JoshYates1980
  • 3,476
  • 2
  • 36
  • 57
0

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.

Koopakiller
  • 2,838
  • 3
  • 32
  • 47
MrBliz
  • 5,830
  • 15
  • 57
  • 81