mvc3如何从控制器返回一个列表

时间:2013-12-17 05:37:00

标签: asp.net-mvc-3 list controller

我的视图中有一个列表,但此列表在多个视图中重复使用,列表在所有视图中共享相同的信息

// MyView.cshtml
@Html.DropDownListFor(model => model.type, new SelectList(new List<Object>{ 
                new { Text = "Automotive", Value = "Automotive"},
 new { Text ="Business", Value= "Business"}}}, "Value", "Text"))

这是下拉列表,因为问题是列表有时会发生变化,因此我决定在控制器中创建列表,如果我需要更改我可以在一个地方做的事情,它会改变一切,无论如何我是想知道如何从控制器使用不同的actionResult使列表显示在 MyView.cshtml

 public ActionResult articleList()
    {
        var mylist = new List<articledrop>
       {
           new articledrop{ Text = "Automotive", Value = "Automotive"},
           new articledrop{ Text ="Business", Value= "Business"}

       };
        return View(mylist);
    }

如您所见,我已在View articleList.cshtml 中创建了列表,现在如何使用dropdownList将该列表显示在 MyView.cshtml 上。任何建议都会很棒

1 个答案:

答案 0 :(得分:0)

你可以添加一个包含列表的静态类,如下所示:

public static class UtilLists
{
     public static List<articledrop> mylist = new List<articledrop>
     {
         new articledrop{ Text = "Automotive", Value = "Automotive"},
         new articledrop{ Text ="Business", Value= "Business"}
     };
}

查看中,您只需这样称呼它:

@Html.DropDownListFor(model => model.type, 
                      MvcApplication1.UtilLists.mylist.Select(option => new SelectListItem {
                                 Text = option.Text, 
                                 Value = option.Value}), 
                     "Choose..")

让我知道;)

相关问题