使用ASP.NET MVC ViewBag和DropDownListfor时遇到困难

lea*_*ing 1 asp.net-mvc asp.net-mvc-3

我的困难是如何使用ViewBagDropdownListFor

在我的控制器中,我有:

TestModel model = new TestModel();
ViewBag.Clients = model.Clients;
ViewBag.StatusList = model.StatusList;
ViewBag.enumStatus = model.enumStatus;
ViewBag.intClient = model.intClient;
Run Code Online (Sandbox Code Playgroud)

在我的TestModel中

public SelectList Clients { get; set; }       
public SelectList StatusList { get; set; }
public ActiveStatus enumStatus { get; set; }
public int? intClient { get; set; }
Run Code Online (Sandbox Code Playgroud)

在我看来

我想用来DropDownListFor显示ViewBag值,我该怎么做?

Dar*_*rov 10

你可以这样做:

@Html.DropDownListFor(x => x.intClient, ViewBag.Clients)
Run Code Online (Sandbox Code Playgroud)

但我建议你避免使用ViewBag/ViewData并从你的视图模型中获利:

public ActionResult Index()
{
    var model = new TestModel();
    model.Clients = new SelectList(new[]
    {
        new { Value = "1", Text = "client 1" },
        new { Value = "2", Text = "client 2" },
        new { Value = "3", Text = "client 3" },
    }, "Value", "Text");
    model.intClient = 2;
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

并在视图中:

@Html.DropDownListFor(x => x.intClient, Model.Clients)
Run Code Online (Sandbox Code Playgroud)

  • 我不能使用@ Html.DropDownListFor(x => x.intClient,ViewBag.Clients),因为intClient是一个ViewBag属性,我不能使用ViewBag.intClient (2认同)

Dav*_*Dev 9

就个人而言......我创建了一个List并执行此操作.

public ActionResult SomeAction()
{
    var list = new List<SelectListItem>();
    list.Add(new SelectListItem(){Text = "One", Value="One"});
    list.Add(new SelectListItem(){Text = "Two", Value="Two"});
    list.Add(new SelectListItem(){Text = "Three", Value="Three"});
    list.Add(new SelectListItem(){Text = "Four", Value="Four"});

    ViewBag.Clients = list;

    return View();
}
Run Code Online (Sandbox Code Playgroud)

然后在你看来......

@Html.DropDownListFor(x => x.SomePropertyOnModel, (IEnumerable<SelectListItem>)ViewBag.Clients);
Run Code Online (Sandbox Code Playgroud)

注意Viewbag项目上的强制转换.演员是必需的,因为viewbag不知道对象是什么Viewbag.Client.所以演员阵容是必需的.