Heidel
Heidel

Reputation: 3262

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" />

Upvotes: 12

Views: 43296

Answers (3)

vibs2006
vibs2006

Reputation: 6548

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

@Html.TextBoxFor(m => m.Venue, new { @class = "form-control", @id = "AnyCustomID" })

Upvotes: 1

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

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.

Upvotes: 25

Gorgsenegger
Gorgsenegger

Reputation: 7856

Try

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

Upvotes: 5

Related Questions