【问题标题】:Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>'无法将类型“System.Web.Mvc.SelectList”隐式转换为“System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>”
【发布时间】:2014-02-06 21:17:04
【问题描述】:

我正在尝试将一些值添加到对象的 SelectList 数据成员中,但出现错误

public ActionResult Create()
    {

        var paf = new ProductAddForm();
        paf.Sizes = new SelectList(m.GetProductSizes());
        paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");

        return View(paf);
    }

那是我的 creat 函数,paf.Sizes / paf.Suppliers 代码不起作用。

我的 productaddform 类:

    public class ProductAddForm
{

    public double MSRP { get; set; }

    public string Name { get; set; }

    public string ProductId { get; set; }

    public ICollection<SelectList> Sizes { get; set; }

    public ICollection<SelectList> Suppliers { get; set; }

    public string UPC { get; set; }


}

还有我在 manager.cs 中的方法

public IEnumerable<SupplierList> GetAllSuppliersList()
    {

        var fetchedObjects = ds.Suppliers.OrderBy(n => n.Name);

        var Suppliers = new List<SupplierList>();

        foreach (var item in fetchedObjects)
        {

            var s = new SupplierList();
            s.Name = item.Name;
            s.Id = item.Id;

            Suppliers.Add(s);
        }

        return (Suppliers);

    }

    public List<string> GetProductSizes()
    {

        return new List<string>() { "Small", "Medium", "Large" };
    }

怎么了?

【问题讨论】:

  • paf.suppliers 接受 ICollection&lt;SelectList&gt; 供应商,但您输入的是单个选择列表 new SelectList(m.GetAllSuppliersList(), "Id", "Name");

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

Suppliers 是SelectList 的集合。所以你需要将项目添加到集合中

改变

paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");

到

paf.Suppliers.Add(new SelectList(m.GetAllSuppliersList(), "Id", "Name"));

【讨论】:

  • @user2981393 请随意接受他的正确回答。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多