如何使用List<>从列表框中的数据库获取数据在as.net MVC中

时间:2014-04-29 08:08:44

标签: c# asp.net-mvc listbox

我是MVC的新手,我在许多网站上搜索从数据库中获取数据并在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
};

我没有得到如何在List中编写查询,请告诉我如何在上面的语法中编写查询......

请帮助我......

已更新

实际上我想显示两个列表框,其中包含来自db的数据,secondlistbox包含来自1stlistbox的所选项目, 我的代码是这样的......

型号:

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>'

2 个答案:

答案 0 :(得分:0)

return (from c in db.Product
                     where c.ProductId == ProductId
                     select c).ToList();

您只需添加 .ToList()即可返回列表

答案 1 :(得分:0)

示例:

YourEntity db = new YourEntity();

var data = (from m in db.Models
             select m.Name);

List<string> list = data.ToList<string>();