I have been banging my head for 2 days now with Html.DropDownListFor and MVC3.
I have been successful in creating a drop down list and successfully updating the database based on it.
I create a drop down list for area
1 - NewYork
2 - London
3 - Paris
etc
The problem occurs when creating a edit page where the user can change the previous choice. I am trying to show the previous selected value in the drop down.
My code is as follows:
Controller:
//
// GET: /MyHome/UpdateProfile
public ActionResult UpdateProfile()
{
var userProfile = websiteRepository.GetProfileForLoggedUser();
UpdateProfileViewModel viewModel = new UpdateProfileViewModel
{
AreaLookUps = websiteRepository.GetAreaLookUpSelectList(userProfile.Area),
UserProfile = userProfile
};
return View("UpdateProfile", viewModel);
}
The GetAreaLookUpSelectList method
public IEnumerable<SelectListItem> GetAreaLookUpSelectList(int selectedId)
{
var areaLookUps = from p in db.AreaLookUp
orderby p.AreaLookUpDescription
select new SelectListItem
{
Text = p.AreaLookUpDescription,
Value = SqlFunctions.StringConvert((double)p.AreaLookUpId),
Selected = p.AreaLookUpId == selectedId
};
return areaLookUps;
}
View
@model NPLHWebsite.ViewModels.UpdateProfileViewModel
<div class="editor-label">
@Html.LabelFor(model => model.UserProfile.Area)
@Html.DropDownListFor(model => model.UserProfile.Area, Model.AreaLookUps, "--Select Area--")
</div>
ViewModel
public class UpdateProfileViewModel
{
public UserProfile UserProfile { get; set; }
public IEnumerable<SelectListItem> AreaLookUps { get; set; }
}
Please help me display a selected value. Say "London" in the dropdownlist, if that option was selected while creating the profile. The database stores the value of 2 to represent London.