首页 > Web开发 > 详细

关于MVC中DropDownListFor的一个bug

时间:2014-02-26 02:16:10      阅读:414      评论:0      收藏:0      [点我收藏+]

如以下代码:

bubuko.com,布布扣
 1 //后台 代码
 2 ViewData["source_type"] = new List<SelectListItem>
 3             {
 4                 new SelectListItem() {Text = "测试1", Value = "1"},
 5                 new SelectListItem() {Text = "测试2", Value = "2"},
 6                 new SelectListItem() {Text = "测试3", Value = "3"},
 7                 new SelectListItem() {Text = "测试4", Value = "4"}
 8             };
 9             return View(new thr_channel_commodity_report { source_type = 4 });
10 //前台代码:
11 @Html.DropDownListFor(x=>x.source_type,ViewData["source_type"] as IEnumerable<SelectListItem>)
bubuko.com,布布扣

使用ViewDate传递数据 并使用“source_type”这个名称 导致页面的下拉框不能正确显示 当前model值

原因:

bubuko.com,布布扣
源码 最底层这个方法 : 
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
其中有段代码:
if (!usedViewData) {
                if (defaultValue == null) {
                    defaultValue = htmlHelper.ViewData.Eval(fullName);
                } 
            }
其中的
htmlHelper.ViewData.Eval(fullName);
bubuko.com,布布扣

这个Eval 存在问题。 当使用ViewData传递数据时候 而且和第一个参数表达式名称相同时   此段代码 获取的值为:整个数组 所以 。。。 如果你使用ViewData["source_type2"]只要和表达式名字不相同即可

建议:

1、不要使用ViewData或者ViewBag传递数据给DropDownList

2、如果必须使用ViewData请使用 名称非表达式名称

关于MVC中DropDownListFor的一个bug

原文:http://www.cnblogs.com/rufus-hua/p/3567174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!