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

廉价感情. 提交于 2019-11-30 02:19:39

问题


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" } })

回答1:


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
}  



回答2:


I explicitly set the dataValueField and dataTextField names.

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

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



来源:https://stackoverflow.com/questions/35755862/why-i-am-getting-system-web-mvc-selectlistitem-in-my-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!