Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I believe I have bound my data correctly, but I can't seem to get my text property for each SelectListItem to show properly.

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" } })
like image 905
default_noob_network Avatar asked Mar 02 '16 18:03

default_noob_network


People also ask

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.

What is difference between DropDownList and DropdownListFor?

DropdownListFor is support strongly type and it name assign by lambda Expression so it shows compile time error if have any error. DropdownList not support this.


1 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 with the DropDownListFor helper method

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

So when you post your form, you can inspect the SelectedLicenseName property

[HttpPost]
public ActionResult Create(Licenses model)
{
  //check model.SelectedLicenseName
}  
like image 101
Shyju Avatar answered Sep 28 '22 07:09

Shyju