Why am I getting "System.Web.Mvc.SelectListItem" in my DropDownList?

I believe that I bound my data correctly, but I can’t show that my text property for each SelectListItem is displayed correctly.

My model:

public class Licenses { public SelectList LicenseNames { get; set; } public string SelectedLicenseName { get; set; } } 

Controller:

 [HttpGet] public ActionResult License() { try { DataTable LicsTable = BW.SQLServer.Table("GetLicenses", ConfigurationManager.ConnectionStrings["ProfressionalActivitiesConnection"].ToString()); ProfessionalActivities.Models.Licenses model = new ProfessionalActivities.Models.Licenses(); model.LicenseNames = new SelectList(LicsTable.AsEnumerable().Select(row => new SelectListItem { Value = row["Description"].ToString(), Text = "test" })); return PartialView("_AddLicense", model); } catch (Exception ex) { var t = ex; return PartialView("_AddLicense"); } } 

View:

 @Html.DropDownList("LicenseNames", new SelectList(Model.LicenseNames, "Value", "Text", Model.LicenseNames.SelectedValue), new { htmlAttributes = new { @class = "form-control focusMe" } }) 
+5
source share
2 answers

Use the Items property of your LicenseNames property, which is of type SelectList

 @Html.DropDownList("SelectedLicenseName", new SelectList(Model.LicenseNames.Items, "Value", "Text", Model.LicenseNames.SelectedValue)) 

Or using the DropDownListFor helper method

 @Html.DropDownListFor(d=>d.SelectedLicenseName, Model.LicenseNames.Items as List<SelectListItem>) 

So when you publish your form, you can check the SelectedLicenseName property

 [HttpPost] public ActionResult Create(Licenses model) { //check model.SelectedLicenseName } 
+7
source

I explicitly set the names dataValueField and dataTextField .

 new SelectListItem { Value = row["Description"].ToString(), Text = "test" }), "Value", "Text"); 

Then there is no need to write Model.LicenseNames.Items as List<SelectListItem> in your views (as suggested in your accepted answer).

0
source

Source: https://habr.com/ru/post/1244316/


All Articles