How to use a ViewBag to create a dropdownlist?
Asked Answered
S

9

43

Controller:

public ActionResult Filter()
{
    ViewBag.Accounts = BusinessLayer.AccountManager.Instance.getUserAccounts(HttpContext.User.Identity.Name);
    return View();
}

View:

<td>Account: </td>
<td>@Html.DropDownListFor("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>

ViewBag.Accounts contains Account objects which have AccountID, AccountName and other properties. I would like a DropDownList called accountid (so that on Form Post I can pass the selected AccountID) and the DropDownList to display the AccountName while having the AccountID as value.

What am I doing wrong in the view code?

Sanderlin answered 16/5, 2013 at 18:37 Comment(3)
View code is obviously not working/not good.Sanderlin
What does getUserAccounts return? Does it return collection of the object?Koheleth
yes. IEnumerable<CommonLayer.Account>Sanderlin
K
76

You cannot used the Helper @Html.DropdownListFor, because the first parameter was not correct, change your helper to:

@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

@Html.DropDownListFor receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.

Here's the documentation

If your View it's strongly typed to some Model you may change your code using a helper to created a strongly typed dropdownlist, something like

@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
Kalbli answered 16/5, 2013 at 19:2 Comment(1)
Thanks, I have changed it to the following: @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts) however the name being displayed is the object name not the actual accounts namesSanderlin
S
27

Try:

In the controller:

ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");

In the View:

@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })

or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".

Surfeit answered 16/12, 2016 at 16:49 Comment(1)
How do I retrieve the value from the DropDownList to the controller?Dipterous
K
5

I do the following

In my action method

    Dictionary<string, string> dictAccounts = ViewModelDropDown.GetAccounts(id);
    ViewBag.accounts = dictAccounts;

In my View Code

 Dictionary<string, string> accounts = (Dictionary<string, string>)ViewBag.accounts;
 @Html.DropDownListFor(model => model.AccountId, new SelectList(accounts, "Value", "Key"), new { style = "width:310px; height: 30px; padding 5px; margin: 5px 0 6px; background: none repeat scroll 0 0 #FFFFFF; vertical-align:middle;" })
Koheleth answered 16/5, 2013 at 18:55 Comment(0)
S
3

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

Steadfast answered 3/8, 2016 at 5:3 Comment(0)
M
1

Try using @Html.DropDownList instead:

<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>

@Html.DropDownListFor expects a lambda as its first argument, not a string for the ID as you specify.

Other than that, without knowing what getUserAccounts() consists of, suffice to say it needs to return some sort of collection (IEnumerable for example) that has at least 1 object in it. If it returns null the property in the ViewBag won't have anything.

Marylyn answered 16/5, 2013 at 19:1 Comment(0)
D
1

Marie McDonley solution is good enough, but I've read comments here saying that it is not a good approach. I made my own, very similar to Marie's, but using ViewData.

Note: If you want to now more about ViewData, go to System.Web.Mvc.ControllerBase or to System.Web.Mvc.ViewDataDictionary.

Solution Using ViewData

Controller

List<SelectListItem> Lista= new List<SelectListItem>();

Lista.Add(new SelectListItem { Text = "Select option", Value = "0", Selected = true });

for (int i = 1; i <= 5; i++) {
    string j = String.Format("{0}", i);
    Lista.Add(new SelectListItem { Text = j, Value = j });
}

ViewData["YourList"] = Lista;

View

@Html.DropDownList(
    "id_for_select_element", // eg: "yourId", the name of the form field
    (IEnumerable<SelectListItem>)ViewData["YourList"], // your list items
    "option_label", // eg: "Select Value"
                    // if null, you can place your own text at value 0
                    // as I did above.
    new { @class = "form-control form-select" } // object for html attributes
                                                // In this case, those are Bootstrap classes
)

Result

enter image description here

Dipterous answered 1/7, 2022 at 22:51 Comment(0)
O
0

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // استفاده از ویومدل برای نمایش چند مدل در ویو
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('ثبت شد')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('اشکال در ثبت')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // برای استفاده کردن از چند مدل در یک ویو
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // کد بلااستفاده فقط برای ازمایش اکسپشن این را نوشتم

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}
Okhotsk answered 5/9, 2017 at 8:13 Comment(0)
R
0
@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })
Rawhide answered 29/1, 2020 at 9:13 Comment(1)
I do the followingRawhide
S
-1
public ActionResult Index()
{
    
    List<SelectListItem> items = new List<SelectListItem>();
    items.Add(new SelectListItem { Text = "Item 1", Value = "1" });
    items.Add(new SelectListItem { Text = "Item 2", Value = "2" });
    items.Add(new SelectListItem { Text = "Item 3", Value = "3" });

    
    ViewBag.Items = items;

    return View();
}

@Html.DropDownList("dropdownList", (IEnumerable<SelectListItem>)ViewBag.Items)
Sagittate answered 15/12, 2022 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.