如何使用List<>;在as.net MVC中
本文关键字:net as MVC gt 何使用 List lt | 更新日期: 2023-09-27 18:00:35
我是MVC的新手,我在很多网站上搜索过从数据库中获取数据并显示在Listbox中,但我没有得到任何正确的答案,在每个网站上都有类似于Listbox的硬编码示例。
public List<Product> allProducts = new List<Product>
{
new Product(1, "Games Console", "Fun for all the family", 199.99m),
new Product(2, "MP3 player", "Listen to your favourite tunes on the move", 99.99m),
new Product(3, "Smart Phone", "Apps, apps, apps", 399.99m),
new Product(4, "Digital Photo frame", "All your photos in one beautiful frame", 49.99m),
new Product(5, "E-book reader", "Take your favourite books on the move with you", 149.99m),
new Product(6, "DVD Box Set", "All of season one plus exclusive extras", 39.99m)
};
但我想像这样显示数据库中的数据;
public List<Model> allModels = new List<Model>
{
//Query to fetch data from database
};
我不知道如何在列表中写查询,请告诉我如何在上面的语法中写查询…
请帮帮我…。
更新
实际上,我想显示两个列表框,一个包含来自数据库的数据,第二个列表框包含来自第一个列表框的选定项目,我的代码是这样的…
型号:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public string Class { get; set; }
}
我在数据库中添加了一些数据
ViewModels类:
public class ViewModel
{
public List<Model> AvailableModel { get; set; }
public List<Model> RequestedModel { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
我遵循以下条款:[http://www.codeproject.com/Articles/136730/ASP-NET-MVC-Basics-Working-with-ListBoxes][1]
作为您建议的代码:
var data = (from m indb.Models
selectm.Name);
List<Model>modellist = data.ToList();
我写了这个它抛出一个错误:
Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<DemoListBox.Models.Model>'
示例:
YourEntity db = new YourEntity();
var data = (from m in db.Models
select m.Name);
List<string> list = data.ToList<string>();
return (from c in db.Product
where c.ProductId == ProductId
select c).ToList();
您只需要添加.ToList()即可返回List