循环表单集合并将数据添加到列表中



我有以下代码,我正在使用这些代码从表单集合中获取值

List<FlowSettings> lst = new List<FlowSettings>();
string[] IsVisible  =  fc["IsVisible"].Split(',');
string[] Editable   = fc["Editable"].Split(',');
string[] Revisable  = fc["Revisable"].Split(',');
string[] tbl        = fc["tblId"].Split(',');

上面的数组只是为了确保我得到预期的数据。我的问题是,我可以在表单集合上循环,但不能将值取出并添加到我的列表中。

foreach (var _key in fc.Keys)
{
    var _value = fc[_key.ToString()];
    //lst.Add(new FlowSettings { TblId = Convert.ToInt32(_value[0]),  ChxIsVisible =
    Convert.ToBoolean(_value[1]),
    ChxEditable = true, 
    ChxRevisable = true
    });          
}

IsVisible等中的值有10行,它们是bool,tbl是int

有人能告诉我我缺了什么吗

--------------额外代码------------------

public ActionResult FlowItems(FormCollection fc)

lst在foreach循环中

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);
}

这种方法需要注意。如果col1col2中缺少数据。例如

var col3 = new NameValueCollection
{
    { "IsVisible", "True" },
    { "Editable", "" },
    // { "Revisable", "True" }, Missing this entry
    { "tblId", "102" },
};

然后循环将越界。

问题可能是集合包含逗号分隔的值(我认为这是因为问题开头的Split()),但在for循环中,您直接使用该值,而不使用逗号分隔。所以我想它会试图用值的第二个字符(索引为1)创建一个bool。

试试这个:

        foreach (var _key in fc.Keys)
        {
            var _value = fc[_key.ToString()];
            string[] tokenized = _value.Split(',');
            bool b = Convert.ToBoolean(tokenized[1]);
        }

最新更新