为什么我会收到"System.Web.Mvc.SelectListItem"在我的DropDownList中? [英] Why I am getting "System.Web.Mvc.SelectListItem" in my DropDownList?

查看:141
本文介绍了为什么我会收到"System.Web.Mvc.SelectListItem"在我的DropDownList中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我已经正确绑定了数据,但是似乎无法让每个SelectListItem的文本属性正确显示.

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

我的模特:

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

控制器:

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

查看:

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

推荐答案

使用类型SelectList

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

或使用DropDownListFor辅助方法

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

因此,当您发布表单时,可以检查SelectedLicenseName属性

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

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

这篇关于为什么我会收到"System.Web.Mvc.SelectListItem"在我的DropDownList中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆