DropDownListFor … selected value

2019-04-29 09:44发布

问题:

In my model, I have a list of country : Model.ListCountry. The Country class has some fields : Id, Code, ValueFR, ValueUS

In my model, I have a Customer and this customer has a country : Model.Customer.Country

I tried this :

@Html.DropDownListFor(x => x.Record.Customer.Country, new SelectList(Model.ListCountry, "Code", "FR"), new { id = "lbCountry" })

No idea ?

Thanks,

Update1: In the database, I save the Id, but in the dropdown as "option value" I use the code, and as display fiels ValueFR or ValueUS depending of the language user

回答1:

In order to preselect a value in a dropdown list set the corresponding property to this value in your controller action:

model.Record.Customer.Country = "FR";

As far as the dropdown list generation is concerned the two string arguments you are passing to the SelectList constructor represent the property names of the model corresponding respectively to the Value and Text. So I guess it should be more like this:

@Html.DropDownListFor(
    x => x.Record.Customer.Country, 
    new SelectList(Model.ListCountry, "Code", "ValueFR"), 
    new { id = "lbCountry" }
)

In this example we are using the Code property as Values in the dropdown list and ValueFR property as Text. So in this case you must ensure that you are setting the model.Record.Customer.Country property to some Code that exists in the list and the dropdown will automatically preselect this item.

Another possibility use the following SelectList constructor which allows you to specify a selected value as 4th parameter:

@Html.DropDownListFor(
    x => x.Record.Customer.Country, 
    new SelectList(Model.ListCountry, "Code", "ValueFR", "FR"), 
    new { id = "lbCountry" }
)