lukaszb
lukaszb

Reputation: 169

mvc 3 dropdownlistfor - selected value is always null

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.

Upvotes: 1

Views: 511

Answers (1)

Display Name
Display Name

Reputation: 4732

Its quite possible that rm.GetAllRegionsMapper().ToList() returns you a list with all regionId == null.

Also, why have you defined regionId as nullable? It always will be either key you selected from DropDownList or 0 if non was selected, no reason to have it as null ever.

You very much likely confusing between regionId that is key in the drop down list and the regionId that you trying to fetch after selection is made and posted back. Call the latter one selectedRegionId to avoid confusion.

Hope these few ideas will lead you to the right direction and help you localize your actual problem.

Upvotes: 1

Related Questions