如何从动态下拉列表中选择值(使用视图包绑定)在mvc中。 [英] How to get selected value from dynamic drop down( binded using view bag) in mvc.
本文介绍了如何从动态下拉列表中选择值(使用视图包绑定)在mvc中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有动态下拉列表(值从下拉列表获取并使用viewbag绑定),我想在控制器中选择其值。
我尝试过什么:
控制器:
i have dynamic dropdown (values are fetched from dropdown and binded using viewbag ), whose selected value i want in controller.
What I have tried:
controller:
dt = objCommonClass.GETGAME();
OblListTournamentRegistration = null;
OblListTournamentRegistration = new List<SelectListItem>();
foreach (DataRow dr in dt.Rows)
{
OblListTournamentRegistration.Add(new SelectListItem() { Text = dr["GAME_NAME"].ToString(), Value = dr["GAME_ID"].ToString() });
}
ViewBag.GAME = OblListTournamentRegistration;
查看:
view:
@Html.DropDownListFor(model=>model.TournamentGame, ViewBag.GAME as SelectList, "Select Game", new { @id = "ddlGame", @class = "form-control glyphicon glyphicon-user" })
错误
error
{"There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'TournamentGame'."}
推荐答案
ViewBag.GAME
设置为OblListTournamentRegistration
,这是列表< SelectListItem>
。
因此,ViewBag.GAME as SelectList
返回null
,因为列表< SelectListItem>
不是SelectList
。
列表时传递给DropDownListFor
的项目是null
,它在ViewBag中查找项目
使用与属性名称匹配的键(TournamentGame)。由于不存在这样的密钥,它会抛出你正在获得的(稍微令人困惑)错误。
更改视图以匹配类型您正在使用的项目集合:
ViewBag.GAME
is set toOblListTournamentRegistration
, which is aList<SelectListItem>
.
Therefore,ViewBag.GAME as SelectList
returnsnull
, becauseList<SelectListItem>
is not aSelectList
.
When the list of items passed toDropDownListFor
isnull
, it looks for an item in theViewBag
with a key that matches the property name ("TournamentGame"). Since no such key exists, it throws the (slightly confusing) error that you're getting.
Change your view to match the type of the item collection you're using:
@Html.DropDownListFor(model => model.TournamentGame, (IEnumerable<SelectListItem>)ViewBag.GAME, "Select Game", new { @id = "ddlGame", @class = "form-control glyphicon glyphicon-user" })
这样可行,因为 List< ; T>
实现 IEnumerable< T>
, DropDownListFor
有一个重载,接受 IEnumerable< SelectListItem>
对象作为项目集合 [ ^ ]。
This works, because List<T>
implements IEnumerable<T>
, and DropDownListFor
has an overload which accepts an IEnumerable<SelectListItem>
object as the items collection[^].
这篇关于如何从动态下拉列表中选择值(使用视图包绑定)在mvc中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文