How to use a ViewBag to create a dropdownlist?

后端 未结 7 2228
失恋的感觉
失恋的感觉 2020-12-01 07:35

Controller:

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


        
相关标签:
7条回答
  • 2020-12-01 07:55

    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;" })
    
    0 讨论(0)
  • 2020-12-01 07:57
    @Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })
    
    0 讨论(0)
  • 2020-12-01 07:58

    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.

    0 讨论(0)
  • 2020-12-01 08:01

    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"))
    
    0 讨论(0)
  • 2020-12-01 08:04

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 08:09

    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".

    0 讨论(0)
提交回复
热议问题