Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor

前端 未结 4 1253
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 23:00

My difficulty is how to use ViewBag with DropdownListFor?

In my controller I am having:

TestModel model = new TestModel();
         


        
4条回答
  •  一整个雨季
    2020-12-01 23:55

    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)
    

提交回复
热议问题