I have dropdowlist like this:
public class RegionLine
{
public Nullable<int> regionId { get; set; }
[Display(Name = "Województwo: ")]
public string regionName { get; set; }
}
and controller:
public PartialViewResult getPersonalData()
{
var d = rm.GetAllRegionsMapper();
ViewBag.Regions = new SelectList(rm.GetAllRegionsMapper().ToList(), "regionId", "regionName", "-- select item --");
var user = um.GetUserByLoginMapper(User.Identity.Name);
return PartialView("getPersonalData", user);
}
[HttpPost]
public PartialViewResult UpdatePersonalData(UserLine user)
{
var usr = um.GetUserByLoginMapper(User.Identity.Name);
ViewBag.Regions = new SelectList(rm.GetAllRegionsMapper().ToList(), "regionId", "regionName", "-- select item --");
if (ModelState.IsValid)
{
int status = uda.UpdateEmployeesPersonalData(user.UserId, user.PersonalData.Name, user.PersonalData.LastName,
user.Address.City, user.Address.Street, user.Address.Region.regionId, user.Address.PostCode,
user.PersonalData.KeyWord);
return PartialView("getLabelsPersonalData", user);
}
return PartialView("getPersonalData", usr);
}
the part of view with my dropdownlist:
<tr>
<td>@Html.LabelFor(a => a.Address.Region.regionName)</td>
<td>@Html.DropDownListFor(a => a.Address.Region.regionId, (SelectList)ViewBag.Regions)</td>
</tr>
and when i select some items, on httppost regionId is always null. Please help.
Its quite possible that
rm.GetAllRegionsMapper().ToList()
returns you a list with allregionId == null
.Also, why have you defined regionId as nullable? It always will be either key you selected from
DropDownList
or0
if non was selected, no reason to have it asnull
ever.You very much likely confusing between
regionId
that is key in the drop down list and theregionId
that you trying to fetch after selection is made and posted back. Call the latter oneselectedRegionId
to avoid confusion.Hope these few ideas will lead you to the right direction and help you localize your actual problem.