FormCollection
沒有實現IDictionary(TKey,TValue)
接口,所以你需要通過循環和獲取值。
數據
public class FlowSettings
{
public bool IsVisible { get; set; }
public bool Editable { get; set; }
public bool Revisable { get; set; }
public int TblId { get; set; }
}
private bool ParseBool(string value)
{
return Convert.ToBoolean(EmptyToFalse(value));
}
private int ParseInt(string value)
{
return Convert.ToInt32(EmptyToInvalid(value));
}
private string EmptyToFalse(string value)
{
return string.IsNullOrWhiteSpace(value) ? bool.FalseString : value;
}
private string EmptyToInvalid(string value)
{
return string.IsNullOrWhiteSpace(value) ? "-1" : value;
}
創建
var col1 = new NameValueCollection
{
{ "IsVisible", "True" },
{ "Editable", "True" },
{ "Revisable", "True" },
{ "tblId", "100" },
};
var col2 = new NameValueCollection
{
{ "IsVisible", "True" },
{ "Editable", "" },
{ "Revisable", "True" },
{ "tblId", "101" },
};
var formCollection = new FormCollection
{
col1,
col2
};
var length =
formCollection
.Cast<string>()
.Select(entry => formCollection.GetValues(entry).Length)
.Max();
環
var items = new List<FlowSettings>();
for(var i = 0; i < length; i++)
{
var flowSettings = new FlowSettings
{
IsVisible = ParseBool(formCollection.GetValues("IsVisible")[i]),
Editable = ParseBool(formCollection.GetValues("Editable")[i]),
Revisable = ParseBool(formCollection.GetValues("Revisable")[i]),
TblId = ParseInt(formCollection.GetValues("tblId")[i]),
};
items.Add(flowSettings);
}
有一個警告這種方法。如果有數據從col1
或col2
失蹤。例如
var col3 = new NameValueCollection
{
{ "IsVisible", "True" },
{ "Editable", "" },
// { "Revisable", "True" }, Missing this entry
{ "tblId", "102" },
};
然後循環超出界限。
你能證明什麼'fc'樣子..聲明lst'的'實例,但在代碼是你真正使用它..你有現有的代碼不是很清楚..你可以顯示什麼價值在'fc',你正在分裂,以獲得更好的理解..?謝謝 – MethodMan 2015-02-11 16:28:32
@MethodMan fc在ActionResult中,而lst在foreach循環中 – 2015-02-11 16:35:09
很高興看到這個值看起來像減輕所有猜測工作的例子。 – MethodMan 2015-02-11 16:39:52