Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownListFor ... selected value

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

like image 999
Kris-I Avatar asked Mar 20 '11 21:03

Kris-I


1 Answers

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" }
)
like image 51
Darin Dimitrov Avatar answered Sep 28 '22 03:09

Darin Dimitrov