如何从动态下拉列表中选择值(使用视图包绑定)在mvc中。 [英] How to get selected value from dynamic drop down( binded using view bag) in mvc.

查看:106
本文介绍了如何从动态下拉列表中选择值(使用视图包绑定)在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 to OblListTournamentRegistration, which is a List<SelectListItem>.

Therefore, ViewBag.GAME as SelectList returns null, because List<SelectListItem> is not a SelectList.

When the list of items passed to DropDownListFor is null, it looks for an item in the ViewBag 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆