问题描述
我最初使用IDictonary在我的MVC模型中存储字符串值-如下:
I was originally using a IDictonary to store string values in my MVC model - as below:
public IDictionary<string, string> MyValues { get; set; }
MyValues = new Dictionary<string, string>
{
{"Name", "Joe Bloggs"},
{"Address", "Main Street"}
};
以上是在我的模型构造函数中设置的,当我通过以下操作获得模型时,我还设置了其他值:
The above is set in my model constructor and I also set other values when I get the model by doing:
var model = new MyModel();
model.MyValues .Add("foo", "bar");
在我看来,我有以下内容:
In my view then I have the following:
@{
var myValues = Model.MyValues.ToList();
for (int i = 0; i < myValues .Count(); ++i)
{
@Html.Hidden("Id", myValues[i].Key)
@Html.Hidden("Value", myValues[i].Value)
}
}
我现在需要更改此功能,而不是使用元组来实现该功能
I need to now change this functionality and instead of an IDictoinary implement this with a Tuple
到目前为止,我刚刚将模型中的MyValues更改为:
I have just changed the MyValues in my model so far to be:
public IEnumerable<Tuple<string, string>> MyValues { get; set; }
我不确定如何实现与我的模型构造函数相同的功能,如何在模型中设置其他值,然后在视图中枚举它.
I am not sure how to implement the same functionality I had in my model constructor, setting other values in the model and then enumerating this in the view.
推荐答案
它很简单:
MyValues = new List<Tuple<string,string>>
{
Tuple.Create("Name", "Joe Bloggs"),
Tuple.Create("Address", "Main Street")
};
和:
model.MyValues.Add(Tuple.Create("foo", "bar"));
和:
@{
var myValues = Model.MyValues;
foreach (var tuple in myValues)
{
@Html.Hidden("Id", tuple.Item1);
@Html.Hidden("Value", tuple.Item2);
}
}
但是您应该将MyValues
从IEnumerable
更改为IList
或ICollection
,以表示可以添加.
But you should change MyValues
from being IEnumerable
to IList
or ICollection
better, to say that adding is possible.
这篇关于将值添加到元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!