Reputation: 929
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.
Upvotes: 0
Views: 161
Reputation: 1039588
It looks like the AreaLookUpId
property is a double
which is causing issues when comparing with the selected value because you are using SqlFunctions.StringConvert
and the format might not match exactly.
I would recommend you using integers or guids for id properties. Also you can remove the Selected = p.AreaLookUpId == selectedId
from your GetAreaLookUpSelectList
function. It is enough to set the viewModel.UserProfile.Area
property in your controller action to the corresponding value (which you have already done):
public IEnumerable<SelectListItem> GetAreaLookUpSelectList(int selectedId)
{
return db
.AreaLookUp
.OrderBy(x => x.AreaLookUpDescription)
.ToList()
.Select(x => new SelectListItem
{
Value = x.AreaLookUpId.ToString(),
Text = x.AreaLookUpDescription
});
}
Upvotes: 1