32

How to size the TextArea and assign Model Value to it in Asp.net Mvc

4 Answers 4

34

Try this:

 <%=Html.TextAreaFor(
        m => m.Description, 15, 20, 
        new RouteValueDictionary(new { @class = "someClass"}))%>

Edit:
This wont work as far as I know

<%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15" })%>

because of this:

private const int TextAreaRows = 2;
private const int TextAreaColumns = 20;

// ...





     public static string TextArea(
                this HtmlHelper htmlHelper, string name, 
                IDictionary<string, object> htmlAttributes) {
            Dictionary<string, object> implicitAttributes = new Dictionary<string, object>();
            implicitAttributes.Add("rows", TextAreaRows.ToString(CultureInfo.InvariantCulture));
            implicitAttributes.Add("cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture));
            return TextAreaHelper(htmlHelper, name, true /* useViewData */, null /* value */, implicitAttributes, null /* explicitParameters */, htmlAttributes);

}
Sign up to request clarification or add additional context in comments.

2 Comments

For your 1st example: <%= Html.TextAreaFor(m => m.Description, 15, 20, null) %>
it does't matter add or remove dictionary=) I think question author can handle this=)
25

I found a simple away to achieve this.

Using models annotation razor will be smart enough to generate the textarea.

Model:

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

View:

@Html.EditorFor(model => model.Comments)

Comments

10

Assuming you have a strongly typed view to some model class you could use the following:

<%= Html.TextAreaFor(x => x.SomeProperty, new { rows = "20", cols = "10" }) %>

or:

<%= Html.TextAreaFor(x => x.SomeProperty, 20, 10, new { @class = "foo" }) %>

1 Comment

For your 2nd example: <%= Html.TextAreaFor(x => x.SomeProperty, 20, 10, null) %>
1

Pitfall is @Html.TextAreaFor because it has no overload which allow you assigning a Model Value.

Example 1 :

 @Html.TextAreaFor(m => m.Language, 6, 40, new { @class = "form-control",@value="Tft.WebRole.Properties.Settings.Default.DefaultLanguage"}

Example 1 wont raise exception and wont show any text. Let it down.

Solution :

use @Html.TextArea instead

Example 2:

@Html.TextArea("Language", Tft.WebRole.Properties.Settings.Default.DefaultLanguage, 6, 40, new { @class = "form-control" })

Advice :

You should let down Aspx too because Razor is lighter and equivalent syntax.

Just use @ instead of <%= %>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.