asp.net-mvc 如何使用 ViewBag 创建下拉列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16594958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a ViewBag to create a dropdownlist?
提问by rikket
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.Accountscontains Accountobjects which have AccountID, AccountNameand other properties.
I would like a DropDownListcalled accountid(so that on Form Post I can pass the selected AccountID) and the DropDownListto display the AccountNamewhile having the AccountIDas value.
ViewBag.Accounts包含Account具有AccountID,AccountName和其他属性的对象。我想要一个DropDownList称为accountid(以便在 Form Post 上我可以传递选定的 AccountID)并DropDownList显示AccountName具有AccountIDas 值的while 。
What am I doing wrong in the view code?
我在视图代码中做错了什么?
回答by Jorge
You cannot used the Helper @Html.DropdownListFor, because the first parameter was not correct, change your helper to:
您不能使用 Helper @Html.DropdownListFor,因为第一个参数不正确,请将您的助手更改为:
@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
@Html.DropDownListForreceive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.
@Html.DropDownListFor在第一个参数中接收所有重载中的 lambda 表达式,并用于创建强类型下拉列表。
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"))
回答by Marie McDonley
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".
或者您可以将“null”替换为您希望显示为默认选择器的任何内容,即“选择帐户”。
回答by atbebtg
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;" })
回答by gdmanandamohon
hope it will work
希望它会起作用
@Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })
Here String.Emptywill be the empty as a default selector.
这里String.Empty将空作为默认选择器。
回答by bcr
Try using @Html.DropDownListinstead:
尝试使用@Html.DropDownList:
<td>Account: </td>
<td>@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
@Html.DropDownListForexpects a lambda as its first argument, not a stringfor the ID as you specify.
@Html.DropDownListFor期望 lambda 作为其第一个参数,而不是string您指定的 ID。
Other than that, without knowing what getUserAccounts()consists of, suffice to say it needs to return some sort of collection (IEnumerablefor example) that has at least 1 object in it. If it returns nullthe property in the ViewBag won't have anything.
除此之外,在不知道getUserAccounts()由什么组成的情况下,只需说它需要返回某种集合(IEnumerable例如),其中至少包含 1 个对象。如果它返回nullViewBag 中的属性将不会有任何东西。
回答by Mehdi Shi
Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:
使用 Viewbag 发送列表查看是错误的。在这种情况下,您应该使用 Viewmodel。像这样:
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:
Country_Repository 代码:
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);
}
}
}
回答by user12805062
@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

