Matt D. Webb
Matt D. Webb

Reputation: 3314

How do I add HTML attributes to a Razor HtmlHelper?

I have a general question about some Razor Syntax I keep finding in a project I am working on...

One of the main helpers being used is: @Html.InputFor

They then insert some Lambda for example: @Html.InputFor(_ => _.User)

My question is, how do I work with this helper (I couldn't find any details via a google search) i.e adding attributes like custom css classes?

Is there a better helper I should be using? (I am new to Razor)

Upvotes: 9

Views: 35795

Answers (4)

malkam
malkam

Reputation: 2355

HtmlHelper class is used to create common html controls on page.There is no InputFor extended method.

Ex: Below will create text box for model.Name property.

@Html.TextBoxFor(model => model.Name)

See MSDN for more details.

Upvotes: 0

MiiisterJim
MiiisterJim

Reputation: 429

I might be wrong, but i don't think InputFor is a standard MVC helper. Usually you would use either Html.EditorFor() and define an editor template or for say a string input a Html.TextBoxFor() where you can pass html attributes

e.g. Html.TextBoxFor(m => m.User, new { @class="form-control" })

the @class being necessary as class is a c# keyword

Upvotes: 2

user3383479
user3383479

Reputation:

It can be an custom Extension Method applied for HtmlHelper object. Just Have look in the project in a static class.

This link will be very helpful for you

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157098

I think you mean @Html.TextBoxFor. That extension method can be found in the InputExtensions class.

How to attach an attribute to it? Use the htmlAttributes property:

@Html.TextBoxFor(x => x.User, htmlAttributes : new { @class = "cssclass" } )

Upvotes: 19

Related Questions