如何生成IEnumerable <selectlistitem>并在controller / Edit CudtomerName和CustomerSurname

时间:2015-11-22 13:38:09

标签: asp.net-mvc-5

有谁知道如何生成IEnumerable并在controller / Edit CudtomerName和CustomerSurname中设置Text属性,如下所示?

在付款/创建控制器中我替换;

ViewBag.PaymentCustomer = new SelectList(db.CUSTOMERS, "CUSTID", "CustomerName");

用这个:

    ViewBag.PaymentCustomer = db.CUSTOMERS.ToList().Select(c => new SelectListItem
    {
        Value = c.CUSTID.ToString(),
        Text = string.Format("{0} {1}", c.CustomerName, c.CustomerSurname)
    });

及其工作。但在付款/编辑中是:

ViewBag.PaymentCustomer = new SelectList(db.CUSTOMERS, "CUSTID", "CustomerName", pAYMENT.PaymentCustomer);

ViewBag.PaymentCustomer看起来都一样。付款/编辑它也获得第四个参数“pAYMENT.PaymentCustomer”。我不能在db.CUSTOMERS.ToList()中使用“pAYMENT.PaymentCustomer”。选择...

我试试这个:

        //ViewBag.PaymentCustomer = new SelectList(db.CUSTOMERS, "CUSTID", "CustomerName", pAYMENT.PaymentCustomer);
        ViewBag.PaymentCustomer = new SelectList(db.CUSTOMERS.ToList().Select(c => new SelectListItem
        {
            Value = c.CUSTID.ToString(),
            Text = string.Format("{0} {1}", c.CustomerName, c.CustomerSurname)
        }), pAYMENT.PaymentCustomer);

构建并运行之后。我可以看到下拉列表和内部下拉列表中没有显示Customername和CustomerSurname。它显示“System.Web.Mvc.SelectListItem”。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

    ViewBag.CustomerList = new SelectList(db.CUSTOMERS.ToList().Select(c => new SelectListItem {
        Value = c.CUSTID.ToString(),
        Text = string.Format("{0} {1}", c.CustomerName, c.CustomerSurname),
    }), "Value", "Text", pAYMENT.PaymentCustomer);