• 关于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请使用 名称非表达式名称

  • 相关阅读:
    【面试】Java基础
    GC
    【面试】JVM
    Spooling技术
    数据结构之 平衡二叉树
    二叉树应用
    LINUX设备驱动模型之class
    RTC(x86)
    微内核和单内核
    Linux内核的五大模块
  • 原文地址:https://www.cnblogs.com/rufus-hua/p/3567174.html
Copyright © 2020-2023  润新知