muttley91
muttley91

Reputation: 12674

MVC Razor Form DropDownListFor objects

I have a dropdown list defined as follows:

@Html.DropDownListFor(model => model.Properties, new SelectList(Model.Properties, "PropertyID", "PropertyName"))

When I submit to my form, the model has null in the Properties field. What am I doing wrong? Is my dropdown list incorrectly defined?

Upvotes: 1

Views: 2268

Answers (2)

Aleksandr Ivanov
Aleksandr Ivanov

Reputation: 2786

It's not clear what type is your Properties object, but looking at the name I guess that is some kind of collection.

Usually DropDownList has only one value. So you should have something like that in your model:

public int PropertyId { get; set; }

And then in your view:

@Html.DropDownListFor(model => model.PropertyId , new SelectList(Model.Properties, "PropertyID", "PropertyName"))

So when post occurs you can get selected item from this property.

Upvotes: 1

Praveen Paulose
Praveen Paulose

Reputation: 5771

@Html.DropDownListFor(model => model.SelectedProperty, new SelectList(Model.Properties, "PropertyID", "PropertyName"))

The selected value of your DropDownList would go into a different property i.e. model.SelectedProperty. This property should be of the same type as PropertyID (presumably int)

Upvotes: 0

Related Questions