Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor

You could do this:

@Html.DropDownListFor(x => x.intClient, ViewBag.Clients)

But I would recommend you to avoid ViewBag/ViewData and profit from your view model:

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);
}

and in the view:

@Html.DropDownListFor(x => x.intClient, Model.Clients)

Personally...I create a List and do this.

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();
}

and then in your view...

@Html.DropDownListFor(x => x.SomePropertyOnModel, (IEnumerable<SelectListItem>)ViewBag.Clients);

Notice the cast on the Viewbag item. The cast is required because the viewbag has no idea what the object is for Viewbag.Client. So the cast there is required.


@Html.DropDownListFor(x => x.intClient, new SelectList(Model.Clients, "ClientId", "ClientName"), string.Empty);

The ClientId is the value of the dropdown option.

The ClientName is the text of the dropdown option.

The string.Empty at the end adds a blank entry to the dropdown.