简体   繁体   中英

ASP.NET Get Value of DropDownList

I am populating a dropdownlist using this data:

        return _lamb_database.Lambs().Select(lamb => new SelectListItem
        {
            Text = lamb.LambName,
            Value = lamb.LambID.ToString()
        }).ToList();

I am then passing this List to the view using a viewmodel. In the view I am showing the items in the viewmodel using this code:

        @Html.DropDownListFor(m => m.SelectedLamb, Model.Facilities, "Select Lamb")

SelectedLamb is an integer which gives the unique identifer for the lamb in the database. I am trying to pass back the unique identifier for the lamb instead of the lamb's name. You can see in the above that I am trying to get this list to set SelectedLamb.

I am getting this error:

The ViewData item that has the key 'SelectedLamb' is of type 'System.Int32' but must be of type 'IEnumerable'.

Does anyone know how I can get this to work? I have spent so long on this now.

You need to set the Facilities property again after submitting.

[HttpPost]
public ActionResult YourActionName(YourModel model)
{
    model.Facilities = ..; // set again
    return View(model);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM