user5375600
user5375600

Reputation:

dropdownlistfor helper values not appearing when returning a view

I have a view which successfully renders with a dropdownlistfor populated.

        List<SelectListItem> listBuildings = new List<SelectListItem>(context.Buildings.Select(b => new SelectListItem { Value = b.ID.ToString(), Text = b.BuildingName, }).ToList());
        SelectListItem buildingZeroItem = new SelectListItem() { Value = "0", Text = "Select Building" };
        listBuildings.Add(buildingZeroItem);
        model.Building = listBuildings;

It is correctly display in the browser. I then submit my form to a post like this

        @using (Html.BeginForm("Booking", "Common", FormMethod.Post))
            {
               <div class="col-md-6">
                   @Html.LabelFor(m => m.Building)
                   @Html.DropDownListFor(m => m.Building, Model.Building, new { @class = "form-control", @style = "width:100%;" })
              </div>
            }

Here is the post in the controller...

             [HttpPost]
             public ActionResult Booking( BookingViewModel model)
             {
               var myVals= model.Building
             }

There is nothing in model.Building. I'm missing something quite serious here. I have accompanying textfields, their values are passed. Its just the dropdownlistfor helpers values which I cannot find. This is for validation. I wondered if anyone could give me a bit of an explanation as to where I am going wrong. Thank you.

Upvotes: 1

Views: 38

Answers (1)

user449689
user449689

Reputation: 3154

You need to declare a property in your model to assign the value of the selected element of the DropDownList, as follows:

public IEnumerable<SelectListItem> Building { get; set; }
public int SelectedBuildingId { get; set; }

Then you need to use it in the DropDownListFor declaration:

@Html.DropDownListFor(m => m.SelectedBuildingId, Model.Building, new { @class = "form-control", @style = "width:100%;" })

You will get the value of the selected element in that property

Upvotes: 2

Related Questions