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)%>
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)%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With