creating multiline textbox using Html.Helper function

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

MVC4 you should use:

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

Method 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.." })

Method 4

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.

Method 5

In Entity layer:

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

And in view:

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

Method 6

VB.net solution:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x