zoukankan      html  css  js  c++  java
  • 关于MVC中DropDownListFor的一个bug

    如以下代码:

     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>)

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

    原因:

    源码 最底层这个方法 : 
    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);

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

    建议:

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

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

  • 相关阅读:
    2011 年50+优秀的网页设计(下)
    25+令人惊讶的是令人难以置信的WordPress技术支持网站
    2011 漂亮的网站(上)
    2011 美丽的网站(下)
    38 jQuery和CSS多级下拉菜单解决方案(一)
    HTMl代码片段
    30 +漂亮的jQuery菜单导航(一)
    分享几套还算不错的后台模板(有源码下载)
    配 色 方 案
    一个小故事
  • 原文地址:https://www.cnblogs.com/rufus-hua/p/3567174.html
Copyright © 2011-2022 走看看