MVC和DropdownList

时间:2013-11-09 18:29:40

标签: c# asp.net-mvc

我想在我的网页上包含我的对象的下拉列表(从数据库中读取)。

这是我的目标:

public class MyObject
{
    public int id { get; set; }
    public string fileName { get; set; }

    public string browser { get; set; }

    public string protocol { get; set; }

    public string family { get; set; }
}

我的控制器:

public ActionResult Index()
{
    List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
    ViewBag.Files = lList;
    return View();
}

Index.cshtml

@model IEnumerable<MyApplication.Models.MyObject>
@{
    ViewBag.Title = "Index";    
}

不知道如何从这里继续。

1 个答案:

答案 0 :(得分:1)

试试这个

public ActionResult Index()
{
    List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
    ViewBag.Files =new SelectList(list,"Id","fileName)";
    return View();
}

在视图中添加

  @Html.DropDownList("File",new SelectList(ViewBag.Files))