Search code examples
asp.netasp.net-mvcasp.net-mvc-5textarea

TextAreaFor Not Working When Using HtmlAttributes Overload


For some reasons, when I set my TextAreaFor style properties specifically the width property, it is not working, what I mean is the width is not changing, and the Id is not changing as well:

 @Html.TextAreaFor(model => model.AdminSetting.Style, new { htmlAttributes = new 
 { @class = "form-control", @style = "width: 100%;", @id = "HelloWorld" } })

But if I remove the word htmlAttributes and change it to this then it working fine. I really wonder why:

@Html.TextAreaFor(model => model.AdminSetting.Style, 
new { @class = "form-control", @style = "width: 100%;", @id = "HelloWorld" })

Is there reason why my TextAreaFor htmlAttributes not working unless I remove my declaration of htmlAttributes and declare it like this?

 new { @class = "form-control", @style = "width: 100%;", @id = "HelloWorld" })

Instead of this?

new { htmlAttributes = new 
 { @class = "form-control", @style = "width: 100%;", @id = "HelloWorld" } })

I've check the documentation, and I am sure that I am using the correct overload.


Solution

  • Try as shown below:

    @Html.TextAreaFor(m => m.AdminSetting.Style, 
        new { maxlength = 1000, @class = "form-control", @id = "HelloWorld" })
    

    The helpers, Html.TextAreaFor, Html.EditorFor, Html.DisplayFor are unique in that they're what's referred to as "templated helpers". Instead of just spitting out some defined bit of HTML, they're capable of actually using views to determine what their output will be. These views are referred to as "editor templates" or "display templates", respectively. For more information please have a look at Html.EditorFor and htmlAttributes.