所以我有这句话:
string theWhereClause = " levels = '" + LevelItems[SelectedLevel] +
"' AND areas = '" + AreaItems[SelectedArea] + "'";
AreaItems
是Dictionary<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] + "'";
}
}