开发者

Adding an extra data text field in SelectList in MVC

I am using a select list to pass text to the checkbox , What I want is to pass the 2 text fields to the checkboxlist , but Select list doesnt have any options to provide 2 or 3 data text field , I tried to customize it like but cant get the Intellisense working :

 public A开发者_如何学GoctionResult 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);

    }


First, create a class to hold your result:

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

Then, cast your target collection to an actual type:

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

In the Create() method, change the IQueryable<Object> declaration to IQueryable<ApexWorldResult>, and it should work for you...


in addition to my comment

what you need to define is instead of object use "SelectListItem" This is build used for select list items. where you can specify text, value and value. and

Model Definition:

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

And in controller you use:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜