Jay
Jay

Reputation: 1201

Sitecore Update NameValueList Programmatically

Is there anyway to update NameValueList field?

I want to find a key and update its value programmatically. Here is what I tried, but not working.

enter image description here

Sitecore.Data.Fields.NameValueListField data = Model.Rendering.Item.Fields["Name Value List"];
System.Collections.Specialized.NameValueCollection nameValueCollection = data.NameValues;

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    Model.Rendering.Item.Editing.BeginEdit();
    nameValueCollection.Set("123456", "New Value");
    Model.Rendering.Item.Editing.EndEdit();
}

Any help please...

Upvotes: 1

Views: 361

Answers (1)

nickwesselman
nickwesselman

Reputation: 6890

Looking at the NameValueListField in dotPeek, the NameValues property does not pass a reference to the underlying data, but rather an object containing the parsed values. If you make a change to the NameValueCollection, you need to set it back on the field. So something like this:

Sitecore.Data.Fields.NameValueListField data = Model.Rendering.Item.Fields["Name Value List"];
System.Collections.Specialized.NameValueCollection nameValueCollection = data.NameValues;

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    Model.Rendering.Item.Editing.BeginEdit();
    nameValueCollection.Set("123456", "New Value");
    data.NameValues = nameValueCollection;
    Model.Rendering.Item.Editing.EndEdit();
}

Unrelated: You appear to be editing a value in a Sitecore MVC rendering. Keep in mind a couple things:

  • By default, this will be the web database, and the values will be overwritten on publish
  • Writing to the Sitecore database is very slow and usually a bad idea in public-facing web pages that may be under even minor amounts of traffic load

Upvotes: 1

Related Questions