I have a Razor page with a drop down list inside a form:
@using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { @id = "ProductsByOwners" }))
{
@Html.Label("Choose product owner: ")
@Html.DropDownList("OwnerList", (SelectList)ViewBag.OwnerList, new { @onchange = "this.form.submit();" })
}
The selected value of my SelectList is not being carried over to the DropDownList. I’ve debugged and stepped through the code and found that (SelectList)ViewBag.OwnerList evaluates properly and has the expected value selected, but the resulting HTML does not have any of the option tags selected.
Can anyone see what I’m doing wrong here?
UPDATED
Here is how the SelectList is created in my action:
ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);
The result has the value indicated by values["OwnerList"] selected.
Thanks!
You are not using the DropDownList helper properly. In order to create a dropdownlist you need 2 things:
In your example you have only one of those 2 things (the second). Your first argument is called
OwnerListand you haveViewBag.OwnerListpassed as second argument.So:
Obviously I would recommend you using strongly typed views ans view models. And obviously get rid of the weakly typed ViewBag/ViewData/ViewCrap.
So start by designing a view model to meet the requirements of your view (which from what you have shown so far is to display a dropdownlist):
then a controller:
and you have a corresponding strongly typed view: