开发者

Asp.net MVC TextArea

开发者 https://www.devze.com 2023-01-31 15:06 出处:网络
How to size the TextArea and assign Model Value to it in Asp.n开发者_如何学编程et MvcTry this:

How to size the TextArea and assign Model Value to it in Asp.n开发者_如何学编程et Mvc


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);

}


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)


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" }) %>


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 <%= %>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号