hello hello - 14 days ago 5
C# Question

Get selected value from SelectItemList

I'm trying to use

SelectListItem
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
model.CodeDropDown.ToString()
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
ViewModel
class that looks like this:

public class HomeViewModel
{
[Required]
[DisplayName("Code")]
public IEnumerable<SelectListItem> CodeDropDown { get; set; }
public string SelectedValue { get; set; }
}


I'm filling up the dropdown using this
Controller


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
SelectListItem
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

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. 
Comments