ASP MVC.NET - 如何绑定 KeyValuePair? [英] 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)%>
推荐答案
KeyValuePair
是一个结构体,而不是一个类,所以每次调用你的Stuff
属性返回原始 KeyValuePair
的副本.因此,当您绑定到 Model.Stuff.Value
和 Model.Stuff.Key
时,您实际上是在处理 KeyValuePair
,其中没有一个来自您的模型.因此,当它们更新时,它不会更新模型中的 Stuff 属性... QED
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
顺便说一下,Key 和 Value 属性是只读的,所以你不能修改它们:你必须替换 KeyValuePair
实例
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 :
型号:
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); }
}
查看:
<%=Html.Text("Stuff", Model.StuffValue)%>
<%=Html.Hidden("Model.StuffKey", Model.StuffKey)%>
这篇关于ASP MVC.NET - 如何绑定 KeyValuePair?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!