2013-03-25 60 views
0

我想從頁面向Web用戶控件傳遞值列表。如何在Web用戶控件中創建鍵值對屬性

事情是這樣的:

<uc:MyUserControl runat="server" id="MyUserControl"> 
    <DicProperty> 
     <key="1" value="one"> 
     <key="2" value="two"> 
       ... 
    </DicProperty> 
</uc:MyUserControl> 

如何創建某種在Web用戶控制鍵 - 值對屬性(字典,哈希表)的。

回答

0

我已經找到了一種解決方案:

public partial class MyUserControl : System.Web.UI.UserControl 
{ 
    private Dictionary<string, string> labels = new Dictionary<string, string>(); 

    public LabelParam Param 
    { 
     private get { return null; } 
     set 
     { 
      labels.Add(value.Key, value.Value); 
     } 
    } 

    public class LabelParam : WebControl 
    { 
     public string Key { get; set; } 
     public string Value { get; set; } 

     public LabelParam() { } 
     public LabelParam(string key, string value) { Key = key; Value = value; } 
    } 
} 

在頁面上:

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="test" %> 

<test:MyUserControl ID="MyUserControl1" runat="server"> 
    <Param Key="d1" value="ddd1" /> 
    <Param Key="d2" value="ddd2" /> 
    <Param Key="d3" value="ddd3" /> 
</test:MyUserControl> 
0

您可以創建背後的用戶控件的代碼中的一個公共Dictionary屬性:

public Dictionary<int, string> NameValuePair { get; set; }

然後在創建新的用戶控件形式的代碼隱藏,你可以填充該新屬性:

Dictionary<int, string> newDictionary = new Dictionary<int, string>(); 

newDictionary.Add(1, "one"); 
newDictionary.Add(2, "two"); 
newDictionary.Add(3, "three"); 

MyUserControl.NameValuePair = newDictionary; 
+0

就我而言,我不能落後,所以我必須在我的例子做到這一點從正面像訪問或更改代碼。謝謝。 – drazen 2013-03-26 09:22:12

+0

啊。在這種情況下,您可以簡單地使用控件下方的服務器標記來設置值: ' <%Dictionary newDictionary = new詞典(); newDictionary.Add(1,「one」); ... MyUserControl.NameValuePair = newDictionary; %>確保在Dictionary集合的頁面頂部添加<%@ Import Namespace =「System.Collections.Specialized」%>'。在您的控件上創建公共屬性也可以做到這一點。只需使用服務器標籤。 – McCee 2013-03-26 14:32:06

+0

謝謝。這會起作用,但不是在我的情況。我需要在用戶控件加載事件中的字典值,在你的例子中,我沒有在渲染事件中有值的情況(這對我來說是晚了)。 我已經發布了我的解決方案,我最好能在這一刻。它正在工作:) – drazen 2013-03-26 14:50:06