Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC.NET - how to bind KeyValuePair?

Is it possible to bind such kind of property?

public KeyValuePair<string, string> Stuff { get; set; }

I've tried to use following code in the view, but it does not work:

<%=Html.Text("Stuff", Model.Stuff.Value)%>    
<%=Html.Hidden("Model.Stuff.Key", Model.Stuff.Key)%>
like image 606
Andrey Sidorenko Avatar asked Aug 19 '09 15:08

Andrey Sidorenko


1 Answers

KeyValuePair<K,V> is a structure, not a class, so each call to your Stuff property returns a copy of the original KeyValuePair. So, when you bind to Model.Stuff.Value and to Model.Stuff.Key, you are actually working on two different instances of KeyValuePair<K,V>, none of which is the one from your model. So when they are updated, it doesn't update the Stuff property in your model... QED

By the way, the Key and Value properties are read-only, so you can't modify them : you have to replace the KeyValuePair instance

The following workaround should work :

Model :

private KeyValuePair<string, string> _stuff;
public KeyValuePair<string, string> Stuff
{
    get { return _stuff; }
    set { _stuff = value; }
}

public string StuffKey
{
    get { return _stuff.Key; }
    set { _stuff = new KeyValuePair<string, string>(value, _stuff.Value); }
}

public string StuffValue
{
    get { return _stuff.Value; }
    set { _stuff = new KeyValuePair<string, string>(_stuff.Key, value); }
}

View :

<%=Html.Text("Stuff", Model.StuffValue)%>    
<%=Html.Hidden("Model.StuffKey", Model.StuffKey)%>
like image 99
Thomas Levesque Avatar answered Sep 17 '22 14:09

Thomas Levesque