Problem with MVC Html.TextArea overload

I have a form in the MVC view that contains several text fields, drop-down lists and text areas. I use the HTML helper to create these controls, including pre-populating them with View Data if necessary and applying styles through the htmlAttributes parameter.

This works great with TextBox and DropDownLists controls, etc. However, when I add htmlAttributes to TextArea, it stops working, claiming that the best overloaded method has some invalid arguments, the code that crashes:

Html.TextArea("Description", ViewData["Description_Current"], new { @class = "DataEntryStd_TextArea" }) 

Resulting error:

'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextArea' and the best overload of the extension method 'System.Web.Mvc.Html.TextAreaExtensions.TextArea (System.Web.Mvc.HtmlHelper, string, string, object)' has some invalid arguments

For comparison, TextBox calls that work fine:

 Html.TextBox("TelephoneNumberAlternate", ViewData["TelephoneNumberAlternate"], new { @class = "DataEntryStd_TextBox" }) 

I tried to explicitly reference TextAreaExtensions.TextArea and include the HtmlHelper argument, but that didn't matter.

For reference, calling TextArea works fine without the htmlAttributes parameter. In addition, I tried to specify a name / value dictionary for the class attribute, however this has the same problem.

Any ideas what I'm doing wrong?

+4
source share
2 answers

It always seems to me that these error messages do not tell you which of the arguments does not match.

Have you tried this?

 Html.TextArea("Description", ViewData["Description_Current"].ToString(), new { @class = "DataEntryStd_TextArea" }) 

I ask that ViewData["Description_Current"] is of type Object , and there is an overload with the signature Html.TextArea(String, Object) - although the object in this case represents the html attributes. That is why the compiler does not complain until you add the html attributes as the third parameter - before that the second parameter can be Object , but as soon as you add the third parameter, the second should be a String .

+12
source

You need to pass the value of ViewData ["Description_Current"] to the string, because this method requires a signature (string, string, object) not (string, object, object). TextBox works because there is a signature using html attributes that accepts (string, object, object).

 <%= Html.TextArea( "Name", (string)ViewData["Value"], new { @class = "klass" } ) %> 

Docs for HtmlHelper.TextBox and HtmlHelper.TextArea are available on MSDN.

+3
source

Source: https://habr.com/ru/post/1285807/


All Articles