2

I have a ViewData value taken from an ExpandoObject like this in a Controller:

public ActionResult CountryData()
{
     string json = "{\"Countries\":[{\"CountryId\":1,\"Country\":\"USA\",\"Description\":\"North America\"},{\"CountryId\":2,\"Country\":\"Russia\",\"Description\":\"Europe\"},{\"CountryId\":3,\"Country\":\"Argentina\",\"Description\":\"South America\"}]}";    

     dynamic values = deserializeToDictionary(json);
     ViewData[key2] = values[key2];  //the key is "Countries"
     return View();
}


private Dictionary<string, object> deserializeToDictionary(string JsonString)
{
        dynamic dataObj = new ExpandoObject();
        var values = dataObj as IDictionary<string, object>;
        values = JsonConvert.DeserializeObject<ExpandoObject>(JsonString); 

        Dictionary<string, object> values2 = new Dictionary<string, object>();
        foreach (KeyValuePair<string, object> d in values)
        {
            if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
            {
                values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
            }
            else
            {
                values2.Add(d.Key, d.Value);
            }

        }
        return values2;
}

Note: Code lifted from SO.

I've tried several ways of referencing it inside a template but can't seems to make it work.

(a) I've tried the normal Dictionary lookup:

  <select name="Countries" >
    <option value=""></option>
    $Countries:{Country
    <option  title="$Country["Capital"]$" $if(Country["Selected"]="")$ selected="selected" $endif$ value="$Country["CountryId"]$">$Country["Name"]$</option>
    }$
  </select> 

and

<select name="Countries" >
    <option value=""></option>
    $Countries:{Country
    <option  title="$Country[2]$" $if(Country[3]="")$ selected="selected" $endif$ value="$Country[0]$">$Country[1]$</option>
    }$
</select> 

(b) Tried as well the normal way of referencing strong-typed Value/Data Transfer objects

<select name="Countries" >
    <option value=""></option>
    $Countries:{Country
    <option  title="$Country.Capital$" $if(Country.Selected="")$ selected="selected" $endif$ value="$Country.CountryId$">$Country.Name$</option>
    }$
</select> 

Both didn't work. So how is it done?

Note: I would prefer not using a strongly-type object with hard-coded property names.

Thanks.

Community
  • 1
  • 1
Noble_Bright_Life
  • 569
  • 3
  • 9
  • 16

0 Answers0