Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify attributes for a Html.TextBox helper while maintaining the value retrieval from ViewData?

Tags:

asp.net-mvc

I am using the Html.TextBox helper to create textboxes. I want to set attributes on the textbox, which I understand is done using the following overload:

Html.TextBox (string name, object value, object htmlAttributes)

However, I want to maintain the functionality where the HTML helper automatically uses the value from either ViewData or ViewData.Model and I do not see a way to just specify the name and the htmlAttributes. Is this possible?

like image 984
BigJoe714 Avatar asked Nov 14 '08 20:11

BigJoe714


People also ask

What is the difference between textbox and TextboxFor in MVC?

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view. You can do the same things with both, but you should use typed views and TextboxFor when possible.


2 Answers

[EDIT] After looking at the source code, it appears that all you need to do is specify the value as null in the signature that takes a name, value, and htmlAttributes. If the value is null, it will attempt to use the value from the ViewData.

Html.TextBox( "name", null, new { @class = "css-class" } ); 
like image 103
tvanfosson Avatar answered Nov 09 '22 17:11

tvanfosson


try this for razor

@Html.TextBox("name", "", new {@class = "css-class", @onclick = "alert('demo');"}); 
like image 25
VnDevil Avatar answered Nov 09 '22 17:11

VnDevil