Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Petras Surna 90 posts 144 karma points
    Aug 22, 2020 @ 15:32
    Petras Surna
    0

    How to SetValue for a Dropdownlist value programmatically in Umbraco 8

    I am trying to use SetValue on IContent to programmatically set the value of a dropdown list. I can set the value of Textboxes no issue but not Dropdownlists.

    I have seen solutions for version 7 but I can't find anything for version 8

    private void SetDropDownListValue(IContent content, int dropDownListDataTypeId, string propertyName, string prevalue)
    {
      var dropdown = _DataTypeService.GetAll().First(x => x.Id == dropDownListDataTypeId);
    
      IDataType dataType = _DataTypeService.GetDataType(dropdown.Id);
    
      //valueList looks good, can see all prevalues
      ValueListConfiguration valueList = (ValueListConfiguration)dataType.Configuration;
    
      ValueListItem item = valueList.Items.SingleOrDefault(i => i.Value == prevalue);
    
      if (item != null)
      {
        //item.Id looks good, a simple integer but content crash in backoffice
        //item.Value looks correct too
        content.SetValue(propertyName, item.Id);
      }
    }
    

    I get this in the backoffice when viewing this contententer image description here

    Version 7 solution: https://our.umbraco.com/forum/developers/api-questions/54462-Set-value-of-UmbracoDropDown-programatically

  • Petras Surna 90 posts 144 karma points
    Aug 23, 2020 @ 02:21
    Petras Surna
    102

    I worked out the problem. SetValue has to be called like this:

        content.SetValue(propertyName, "['" + item.Value + "']");
    
  • Alex Skrypnyk 6131 posts 23950 karma points MVP 7x admin c-trib
    Nov 30, 2020 @ 12:03
    Alex Skrypnyk
    4

    Little bit better:

    content.SetValue(propertyName, JsonConvert.SerializeObject(new[] { item.Value }););
    
Please Sign in or register to post replies

Write your reply to:

Draft