I'm having trouble with my DropDownListFors that I'm hoping you can help me with. I'm guessing it's one of those things that you either know or you don't.
The problem is I have a Countries table in my database which has a list of countries in it. The behaviour I would like from my drop down is to create a foreign key reference in my Address table pointing to the county selected in the drop down. The behaviour I'm getting is that the foreign key in my Address table is pointing to a new entry in the Country which is totally unwanted.
Can anyone explain how to do this? I'm not sure what code you guys would like to see so please let me know if you can help.
=== More information ===
Ok, I have a view model class like this:
public class CountryViewModel
{
public int CountryId { get; set; }
public string Name { get; set; }
}
and in my view I have a drop down list like this:
@Html.DropDownListFor(m => m.LegalEntity.Address.Country.CountryId,
new SelectList( Model.LegalEntity.Address.Country,
"CountryId", "Name", Model.LegalEntity.Address.Country.CountryId),
new { @class = "form-control" })
Note that the second line of this does not currently work: I don't know how to get the entire list of countries into this.
My legal entity view model looks like this:
public class LegalEntityViewModel
{
[Key]
public int LegalEntityID { get; set; }
public virtual AddressViewModel Address { get; set; }
public virtual TechnicalContactViewModel TechnicalContact { get; set; }
}
and my address view model looks like this:
public class AddressViewModel
{
[Key]
public int AddressID { get; set; }
...
[Display(Name = "Country")]
public virtual CountryViewModel Country { get; set; }
}
The behaviour I would like is for all the countries to populate the drop down and the selected country to end in my LegalEntityViewModel.AddressViewModel.CountryViewModel.
Help! I've been fiddling with this and refactoring all day!
Looking forward to your responses.
M
There's multiple ways to do this. For example you could load the list of countries in you AddressViewModel.
I.e.
Then in your view do this
You could also load you Countries list with Javascript.
In your controller