在MVC中的SelectList中添加额外的数据文本字段

时间:2011-08-08 15:43:30

标签: asp.net-mvc linq-to-sql asp.net-mvc-2 linq-to-entities selectlist

我正在使用选择列表将文本传递给复选框,我想要的是将2个文本字段传递给复选框列表,但选择列表没有任何选项提供2或3个数据文本字段,我试图自定义它喜欢但不能让Intellisense工作:

 public ActionResult Create()
    {
        IProductRepository ProductResp = new ProductRepository();
        IQueryable<Object> getAllProducts = ProductResp .GetProductsSelectlist();

        List<object> newList = new List<object>();
        foreach (var events in getAllProducts)
            newList.Add(new
            {
                Id = getAllProducts.Name, // I cant get .Name or DateAdded Intellisense here
                Name = getAllProducts.Name + " " + getAllProducts.DateAdded
            });

        ViewData["events"] = new SelectList(newList.ToList(), "Id","Name");
        return View();
    } 

ProductRepository

 public IQueryable<Object> GetProductssSelectlist()
    {

        ApexWorldEntities entity = new ApexWorldEntities();

        var query = from v in entity.Products
                    where v.Date > DateTime.Now 
                    select new { ProductID = v.ID, v.Name , v.Date};
        return query.OrderBy(v => v.Date);

    }

2 个答案:

答案 0 :(得分:1)

首先,创建一个类来保存结果:

public class ApexWorldResult 
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
}

然后,将目标集合转换为实际类型:

var query = from v in entity.Products
            where v.Date > DateTime.Now
            select new ApexWorldResult { ProductID = v.ID, v.Name, v.Date };

Create()方法中,将IQueryable<Object>声明更改为IQueryable<ApexWorldResult>,它应该适合您...

答案 1 :(得分:1)

除了我的评论

你需要定义的是代替对象使用“SelectListItem” 这是用于选择列表项的构建。您可以在其中指定文本,值和值。 和

模型定义:

class FooModel{
 public SelectListItem selectList{get;set;}
...
}

在控制器中你使用:

public ActionResult YourAction(){

 FooModel model = new FooModel();
  //Define your collection of list items
  List<SelectListItem> listItems = new List<SelectListItem>();
            listItems.Add(new SelectListItem(){Selected = false, Text = "Text", Value = "MyValue"});
  //Assign the list to the collection
  model.selectList = new SelectList(listItems);
  //Pass to the view
  return View(model);
}