使用DIctionary Item创建下拉菜单

时间:2012-05-09 17:58:50

标签: asp.net .net asp.net-mvc-3 linq entity-framework

我的观点中有以下内容:

 @Html.DropDownListFor(model => model.Search, new SelectList(Model.SearchOptions))

在我的搜索对象中,我有:

    public List<string> Search { get; set; }

    public Dictionary<string, string> SearchOptions { get; set; }

    public SearchModel GetDropDownOptions(SearchModel model)
    {
        model.SearchOptions = HelperModel.GetRefValues(db, Constants.SEARCH, false);

        return model;
    }

随叫它:

public static Dictionary<String, String> GetRefValues(DBEntities db, string refType, bool addEmpty)
    {

        Dictionary<String, String> res = (from c in db.References
                                          where c.Type == refType
                                          select c).ToDictionary(c => c.Key.ToString(),
                                                                 c => c.Value.ToString());

        if (addEmpty)
            res.Add("", "");

        return res;
    }

但是我得到一个错误说明:“对象引用未设置为对象的实例。”

建议表示赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

您应该验证所有公共方法的参数。所以你的方法:

GetRefValues(DBEntities db, string refType, bool addEmpty)

应该包括检查db是否为空以及refType是否为空。如果你这样做,你将能够看到这两个中的哪一个为空,然后你可以通过追溯来查看它们的初始化位置(或不是,视情况而定)。

相关问题