I am trying to implement editing addresses in my view.
An address has basic strings for street, town etc. It also has a country id. I have a table in my database of countries.
In my controller I create a SelectList for these countries:
ViewBag.Countries = _countryRepo.GetAll().Select(c => new SelectListItem { Text = c.Name, Value = c.Id });
Now in my view I want to be able to use this select list to allow users to select the country.
I originally thought:
@Html.DropDownList("countryId", (IEnumerable<Country>)ViewBag.Countries, "Select")
I have two addresses:
public class Company()
{
public Address HeadOffice { get; set; }
public Address SecondOffice { get; set; }
}
So when displaying the view I need to have the select country shown. I don’t think I can do this in my controller because if I select one like this:
ViewBag.Countries = _countryRepo.GetAll().Select(c => new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == model.HeadOffice.Id ? true : false });
This will only work for the HeadOffice.
From what I can there are two options. Have two different select lists or manually build the select list in the view:
<select name="HeadOffice.CountryId">
@foreach(var c in (IEnumerable<Country>)ViewBag.Countries)
{
<option value="@c.Id" @(c.Id == Model.HeadOffice.Id ? "selected='true'" : "">@c.Name</option>
}
</select>
What is the best way? Both seem wrong and not nice. Is there a better way to approach this problem?
I would use a ViewModel that takes in the list of countries once then expose 2 different lists. This way you only query the database ones but still keep you View clean
ViewModel: