[英]Set the value for Custom Section NameValueSectionHandler in Webconfig
I have custom section Links which I Should edit from UI. 我有自定义部分的链接,应该从UI进行编辑。 While saving I couldn't save the value of the corresponding key.
保存时,我无法保存相应键的值。 It shows "collection is read only" error.
它显示“集合是只读的”错误。 Please help me to resolve this.
请帮助我解决此问题。 Thanks in Advance.
提前致谢。
WebConfig: WebConfig:
<sectionGroup name="Menu">
<section name="Links" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
C# C#
NameValueCollection nameValueCol = (NameValueCollection)ConfigurationManager.GetSection("Menu/Links");
var Key = "Key";
var Value = "Value";
nameValueCol.Set(Key, Value); // Error: collection is read only
so I tried to remove and add the keys still it shows same error. 所以我试图删除并添加键,它仍然显示相同的错误。
nameValueCol.Remove(Key); // Error: collection is read only
ameValueCol.Add(Key, Value);
Can you try it this way: In web.config add section and implement your own section handler 您可以这样尝试吗:在web.config中添加部分并实现自己的部分处理程序
<sectionGroup name="Menu">
<section name="Links" type="Solution.Namepsace.KeyHandler"/>
</sectionGroup>
Then, in your KeyHandler class you can access values for you config: 然后,在KeyHandler类中,您可以访问配置值:
public class KeyHandler: ConfigurationSection
{
#region Configuration Properties
[ConfigurationProperty("KeyValueCollection")]
public string KeyValueCollection
{
get { return this["KeyValueCollection"] as KeyValueCollection; }
}
#endregion
}
Class KeyValueCollection would look like this: 类KeyValueCollection看起来像这样:
[ConfigurationCollection(typeof(KeyValue), AddItemName = "KeyValue")]
public class KeyValueCollection : ConfigurationElementCollection
{
get { return base.BaseGet(index) as KeyValue; }
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
And lastly add KeyValue class: 最后添加KeyValue类:
public class KeyValue: ConfigurationElement
{
#region Constructor(s)
public KeyValue()
{
}
public KeyValue(string key, string value)
{
this.Key= key;
this.Value= value;
}
#endregion
#region Configuration Properties
[ConfigurationProperty("Key", IsRequired = true)]
public string Key
{
get { return this["Key"] as string; }
set { this["Key"] = value; }
}
[ConfigurationProperty("Value", IsRequired = true)]
public string Value
{
get { return this["Value"] as string; }
set { this["Value"] = value; }
}
#endregion
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.