Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor

前端 未结 4 1246
被撕碎了的回忆
被撕碎了的回忆 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:52

    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.

    0 讨论(0)
  • @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.

    0 讨论(0)
  • 2020-12-01 23:54

    Here you can find a good reference: http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题