Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add css class and id in @Html.TextBox mvc4 at the same time

I need to add css class and id in @Html.TextBox mvc4 at the same time. I try

@Html.TextBox("name", new { id = "name"}, new { @class = "text-field" })

but as result I get

 <input class="text-field" id="name" name="name" type="text" value="{ id = name }">

I dont need attribute value here.
I need to get

 <input type="text" value="" name="name" id="name" class="text-field" />
like image 551
Heidel Avatar asked May 20 '13 06:05

Heidel


3 Answers

Correct overload method

public static MvcHtmlString TextBox(
    this HtmlHelper htmlHelper,
    string name,
    Object value,
    Object htmlAttributes
)

you want to use id as HtmlAttribute, so you should use it in HtmlAttributes object. Correct usage of TextBox is:

@Html.TextBox("name", 
    null,
    new { 
        id = "name", 
        @class = "text-field" 
})

if you place id in route object, then id will be a route value.

like image 83
AliRıza Adıyahşi Avatar answered Nov 05 '22 15:11

AliRıza Adıyahşi


Try

@Html.TextBox("name", 
    null,
    new { 
        id = "name", 
        @class = "text-field" 
    })
like image 25
Gorgsenegger Avatar answered Nov 05 '22 14:11

Gorgsenegger


I simply use the new keyword. For example see the following code

@Html.TextBoxFor(m => m.Venue, new { @class = "form-control", @id = "AnyCustomID" })
like image 1
vibs2006 Avatar answered Nov 05 '22 14:11

vibs2006