0

I have a Json something like below: [{"Example temp" : "value"}, {"Example Default" : "", "selected": true}]

I need to fill a dropdown say for example: Dropdown should contain values : Example temp Example Default

And Example Default should be the default selected value,

I tried below code:

JArray jArray = JArray.Parse(jsonstring);

foreach (JObject jObject in jArray.Children<JObject>())
{
   foreach (JProperty jProperty in jObject.Properties())
    {
     string name = jProperty.Name.Trim();
      string value = jProperty.Value.ToString().Trim();
        drpValues.Items.Add(new RadComboBoxItem(name, value));
     }
 }

But "selected" also comes as a dropdown value.

Any help is greatly appreciated.

Thank you so much!

-PT

2
  • Can you change your json format? It would be easier if you can change it to something like [{"Text" : "Example temp", "Value" : "SomeValue"}, {"Text" : "Example Default", "Value" : "", "selected": true}] Commented Feb 15, 2014 at 3:19
  • Thanks for your reply ekad! how do I fill the dropdown with this json, please help! I used this json with my dropdown filling logic and now I have my dropdown values as Example temp, Value, Text, Value Commented Feb 15, 2014 at 4:43

1 Answer 1

1

Assuming there's only one default value, this code should work

JArray jArray = JArray.Parse(jsonStr);

bool isDefault;
string defaultValue;
foreach (JObject jObject in jArray.Children<JObject>())
{
    isDefault = false;

    // check if current jObject contains a property named "selected"
    // and if the value is true
    JProperty p = jObject.Properties().SingleOrDefault(x => x.Name == "selected");
    if (p != null && (bool)p.Value == true)
    {
        isDefault = true;
    }

    foreach (JProperty jProperty in jObject.Properties())
    {
        string name = jProperty.Name.Trim();
        string value = jProperty.Value.ToString().Trim();

        if (name != "selected")
        {
            drpValues.Items.Add(new RadComboBoxItem(name, value));
            if (isDefault)
            {
                defaultValue = value;
            }
        }
    }
}

// set the dropdown selected item
RadComboBoxItem itemToSelect = drpValues.FindItemByValue(defaultValue);
itemToSelect.Selected = true;
Sign up to request clarification or add additional context in comments.

3 Comments

This looks great! Looking for any answer without changing the Json, Want to be less Json for the user for easy update and less confusion, Thanks a lot for your reply.
can this be done without changing the Json? Thank you!
see the edited answer, I think that's what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.