深入Web框架-DropDownList的常见错误

在我们开发中经常会用到DropDownList,但是它又往往难以驾驭,经常会因为绑定值而出错,那么我们该怎么去解决呢,下面我们Web开发平台中给出了常见错误的解决方法。
现象
原因
DropDownList扩展方法
解决
现象

给DropDownList绑值
不是我们的绑值
我们的html前端代码:

<td>
    @Html.DropDownListFor(model => model.QueryModelList[i].FieldTypeMenu, (IList<SelectListItem>)ViewBag.FieldTypeMenu, 
    new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.QueryModelList[i].FieldTypeMenu)
</td>

原因

我们初看该段代码,都是调用的MVC sdk原生函数,从写法上确实是没有问题的,但是为什么在界面上显示的不是我们绑定的初始值呢,我们和Web开发平台MVC开源代码联调了一下,发现 DropDownListFor方法确实是不给绑定初始值的,那怎么办?
看来我们用MVC原生方法是不行了,我们只能为DropDownList扩展一个方法,我们为它绑定好初始值。

DropDownList扩展方法
public static class HtmlExtensionsF
{
    public static MvcHtmlString DropDownListHelperFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
        IEnumerable<SelectListItem> selectList, object selectedValue, string optionLabel, object htmlAttributes)
    {
        foreach (var item in selectList)
        {
            var text = item.Text;
            if (hasSelectedItem(item, selectedValue))
                item.Selected = true;
        }
        if (string.IsNullOrEmpty(optionLabel))
        {
            return htmlHelper.DropDownListFor(expression, selectList, "", htmlAttributes);
        }
        else
        {
            return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
        }
    }
    private static Func<SelectListItem, object, bool> hasSelectedItem = (selectedItem, selectedValue) =>
    {
        if (selectedValue != null)
        {
            var selectedValueString = Convert.ToString(selectedValue);
            if (!string.IsNullOrWhiteSpace(selectedValueString))
            {
                return string.Equals(selectedValueString, selectedItem.Value, StringComparison.CurrentCultureIgnoreCase);
            }
        }
        return false;
    };
}
解决
<td>
    @Html.DropDownListHelperFor(model => model.QueryModelList[i].FieldTypeMenu, (IList<SelectListItem>)ViewBag.FieldTypeMenu, 
    Model.QueryModelList[i].FieldTypeMenu,null, new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.QueryModelList[i].FieldTypeMenu)
</td>

我们调用我们写的扩展方法DropDownListHelperFor,如下图可以看到我们的结果已经呈现出我们想要的,细心的同学应该可以看到我们扩展方法里有一段这样的代码

if (hasSelectedItem(item, selectedValue))
                item.Selected = true;
,对的,这个是我们绑定初始值的关键代码。

正确的DropDownList绑值

本站文章除注明转载外,均为本站原创或翻译,欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,共创和谐网络环境。
转载请注明:文章转载自:华晨软件-云微开发平台 » 深入Web框架-DropDownList的常见错误
本文标题:深入Web框架-DropDownList的常见错误
本文地址:https://www.hocode.com/QAPrefecture/0010.html

相关文章: web框架Ajax实现html下拉框联动 | web框架UI系列--MVC常用控件讲解 | 深入Web框架-JQuey对CheckBox、RadioButton和DropDownList值操作和事件

电话
电话 18718672256

微信
二维码