whiteknight
whiteknight

Reputation: 33

Add Values to Tuple

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

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.

Upvotes: 3

Views: 17167

Answers (1)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

It is as simple as:

MyValues = new List<Tuple<string,string>>
{
    Tuple.Create("Name", "Joe Bloggs"), 
    Tuple.Create("Address", "Main Street")
};

and:

model.MyValues.Add(Tuple.Create("foo", "bar"));

and:

@{
    var myValues = Model.MyValues;

    foreach (var tuple in myValues)
    {
        @Html.Hidden("Id", tuple.Item1);
        @Html.Hidden("Value", tuple.Item2);
    }
}

But you should change MyValues from being IEnumerable to IList or ICollection better, to say that adding is possible.

Upvotes: 6

Related Questions