Question

I have the following code:

@Html.EditorFor(model => model.NoteRateGreaterThan, null, "advSearchInput", null)

The problem is that when a post is done the value i entered for "NoteRateGreaterThan" is not being populated in the model that is sent to the controller. However when I change it back to:

@Html.EditorFor(model => model.NoteRateGreaterThan) 

it works.

I need to be able to use the first code because i need to be able to change the width of the 'editorfor' input and from my research the only way to do this is through css ('advSearchInput' is the class) Any ideas?

Was it helpful?

Solution

I'm not sure what you think your first example does, but it's not that. EditorFor does not have the ability to specify Html attributes, such as class. You must use a more basic method, like Html.TextBoxFor.

The third parameter to EditorFor is htmlFieldName, which is used to disambiguate when you have duplicate element ID's.

That's why your field isn't being populated, because you are changing the name.

EDIT:

As of MVC 5.1, EditorFor now allows you to pass html attributes via the follow syntax:

@Html.EditorFor(model => model.Foo, new { htmlAttributes = new { @class = "whatever" }})

OTHER TIPS

In later versions of MVC EditorFor does have the ability to specify HTML attributes such as class using the following syntax:

@Html.EditorFor(model => model.NoteRateGreaterThan, new { htmlAttributes = new { @class = "form-control" } })

If you want to use an element ID rather than a class in your CSS then you can use the element #NoteRateGreaterThan.

The syntax you were trying to use would set a custom element ID on your editor. This is useful when you have more than one control referencing the same model property. If you wanted to style this control you could use the CSS selector #advSearchInput.

However, as you have noticed, while an editor with a changed ID will get the value from the model, only one of the duplicate controls can be updated back into the model and it will always be the one that does not have a custom ID. Since you do not have a control for this model property without a custom ID no value is written into the model.

Edited to include caveat about versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top