获取密钥时出现奇怪的行为

时间:2016-03-22 13:17:03

标签: c# dictionary asp.net-mvc-5

所以我有这句话:

string theWhereClause = " levels = '" + LevelItems[SelectedLevel] + 
                        "' AND areas = '" + AreaItems[SelectedArea] + "'";

AreaItemsDictionary<string,string>SelectedArea由于某种原因而具有“统计和概率”值,在调试时,它会在此行中断开:

AreaItems[SelectedArea] 

并抛出此错误:

字典中没有给定的密钥。

这是AreaItems[]

中的内容
[0] {[All, All]}
[1] {[Number, Number]}
[2] {[Shape Space and Measures, Shape Space and Measures]}
[3] {[Statistics and Probability, Statistics and Probability]}
[4] {[Algebra, Algebra]}
[5] {[Other, Other]}

但是,如果我对字符串进行硬编码:

AreaItems["Statistics and Probability"]它完美无缺!

我尝试过:

AreaItems[SelectedArea].Trim() 

认为他们是一些隐藏的角色,这仍然无效。

我试过了:

SelectedArea = "Shape Space and Measures";
AreaItems[SelectedArea] 

认为变量中的间距是原因,我错了。它适用于变量中的该值。

我做了一个IF声明来检查它们之间是否有任何区别:

if(SelectedArea == "Statistics and Probability")
{

}

并且它通过IF语句,因此返回true。

然后最后确实有效的是:

string temp = AreaItems[SelectedArea];
string theWhereClause = " levels = '" + LevelItems[SelectedLevel] + 
                        "' AND areas = '" + temp + "'";

这次我所做的只是将AreaItems值存储在不同的字符串(temp)中,并将该字符串放在theWhereClause内并且它有效!

虽然这有效,但我仍然对第一次不这样做感到好奇!

抓住AreaItems[SelectedArea]string temp = AreaItems[SelectedArea]的价值有什么不同会导致这种奇怪的行为?

其他代码可以帮助您:

因此,为了调用此方法,我使用AJAX将值发送到此方法:

    [HttpPost]
    public ActionResult SearchForWorksheets(string level, string area)
    {
        Models.FreeMathsWorksheets freeWorkSheets = new Models.FreeMathsWorksheets();
        freeWorkSheets.SelectedLevel = level;

        // When debugging, at this point the area is "Statistics and Probability"
        freeWorkSheets.SelectedArea = area

        freeWorkSheets.BuildWhereClause();
        List<Models.SearchMathWorksheetsList> WorksheetList = new List<Models.SearchMathWorksheetsList>();
        WorksheetList = freeWorkSheets.ConvertDataTableToList();
        return Json(WorksheetList);
     }

现在由于这行Models.FreeMathsWorksheets freeWorkSheets = new Models.FreeMathsWorksheets();,调用构建dictionarys的方法的构造函数在FreeMathsWorksheets类中被调用:

public class FreeMathsWorksheets
{      

   public string SelectedLevel { get; set; }

   public string SelectedArea { get; set; }

    public FreeMathsWorksheets()
    {
        PopulateAreaDropdown();
    }

    public void PopulateAreaDropdown()
    {
        string theSql = "SELECT * FROM HL_FreeWorksheetAreas";
        IDataAccess da = new DataAccess();
        DataTable dt = da.GetData(theSql);
        AreaItems = new Dictionary<string, string>();

        // Default add an all value
        AreaItems.Add("All", "All");

        foreach (DataRow row in dt.Rows)
        {
            AreaItems.Add(row["area"].ToString(), row["area"].ToString());
        }
    }    

    public void BuildWhereClause()
    {
        string theWhereClause = " levels = '" + LevelItems[SelectedLevel] + "' AND areas = '" + AreaItems[SelectedArea] + "'";
    }
}

0 个答案:

没有答案