ASP MVC.NET - 如何绑定KeyValuePair? [英] ASP MVC.NET - how to bind KeyValuePair?

查看:86
本文介绍了ASP MVC.NET - 如何绑定KeyValuePair?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以结合这些种类的财产?

 公共KeyValuePair<字符串,字符串>东西{搞定;组; }

我试着用下面的视图code,但它不工作:

 <%= Html.Text(东西,Model.Stuff.Value)%GT;
&所述;%= Html.Hidden(Model.Stuff.Key,Model.Stuff.Key)%GT;


解决方案

KeyValuePair&LT; K,V&GT; 是一个结构,而不是一类,因此每次调用您的的东西属性返回的原件及复印件 KeyValuePair <​​/ code>。所以,当您绑定到 Model.Stuff.Value Model.Stuff.Key 时,实际上是工作 KeyValuePair&LT的两个不同的实例; K,V&GT; ,其中没有一个是从你的模型之一。所以,当它们被更新,它不会在你的模型更新的东西属性... QED

顺便说一句,key和value属性是只读的,所以你不能修改它们:你要替换 KeyValuePair <​​/ code>实例

以下的解决方法应该工作:

型号:

 私人KeyValuePair&LT;字符串,字符串&GT; _东东;
公共KeyValuePair&LT;字符串,字符串&GT;东东
{
    {返回_stuff; }
    集合{_stuff =价值; }
}公共字符串StuffKey
{
    {返回_stuff.Key; }
    集合{_stuff =新KeyValuePair&LT;字符串,字符串&GT;(值,_stuff.Value); }
}公共字符串StuffValue
{
    {返回_stuff.Value; }
    集合{_stuff =新KeyValuePair&LT;字符串,字符串&GT;(_ stuff.Key,价值); }
}

查看:

 &LT;%= Html.Text(东西,Model.StuffValue)%GT;
&所述;%= Html.Hidden(Model.StuffKey,Model.StuffKey)%GT;

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)%>

这篇关于ASP MVC.NET - 如何绑定KeyValuePair?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆