hello hello - 1 year ago 65
C# Question

Get selected value from SelectItemList

I'm trying to use

for an MVC project, drop down is populated as I expect it. But when I pass the selected value to a function that accepts string using this
I get
System.Collections.Generic.List 1[System.Web.Mvc.SelectListItem]
which is not a string.

How can I get the selected value as string?

I have a
class that looks like this:

public class HomeViewModel
public IEnumerable<SelectListItem> CodeDropDown { get; set; }
public string SelectedValue { get; set; }

I'm filling up the dropdown using this

public ActionResult Index()
var model = new HomeViewModel();
using (var dbCon = new SomeDBContext())
model.CodeDropDown = dbCon.CodeID.ToList().Select(x => new SelectListItem
Value = x.Name.ToString(), Text = x.CodeDropDown.ToString()
}).DistinctBy(c => c.Value);
return View(model);

I'm trying to use the value from
like this,

public ActionResult Index(HomeViewModel model)
var results = mainDbContext.GetSomeResult(model.CodeDropDown.ToString(), model.Prop2, model.Prop3);
return View(results);

View looks like this:

@Html.DropDownListFor(model => model.SelectedValue, Model.CodeDropDown, "--")

Answer Source

Add one more property (SelectedThingId or something more meaningful) to your HomeViewModel to hold the value of the selected thing from the dropdown.

In your view (you have not posted code for view) have something like this:

@Html.DropDownListFor(x=>x.SelectedThingId, Model.CodeDropDown)

Then in your controller you can get this value using:

model.SelectedThingId; // model is passed into your controller has you have it. 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download