0

I need to create a json string in controller which is as below and send it to view where it gets bind to my js code..

{
    id: 'state',
    label: 'State',
    options: [
        { id: "AL", name: "Alabama" },
        { id: "AK", name: "Alaska" },
        { id: "AZ", name: "Arizona"}            
      ],
    valueSetter: function(rule, value) {
      rule.$el.find('.rule-value-container select')[0].setValue(value);
    }
  }

Id, label and options are to be dynamically generated and I have done that using JObject and JArray as below..

JObject parameter1 = new JObject();
parameter1["id"] ="state";
//And so on...

The part in valueSetter is not dynamic but how do I generate something like this.

Any help is sincerely appreciated.

Thanks

Arnab
  • 2,324
  • 6
  • 36
  • 60

1 Answers1

1

You can return one variable which in itself return one function as a string. Copied from second answer from here

public class JSObj
{
    public string Title { get; set; }
    public int UpperVal { get; set; }
    public int LowerVal { get; set; }
    public object MouseOver
    {
        get
        {
            // use JRaw to set the value of the anonymous function
            return new JRaw(string.Format(@"function(){{ return {0}; }}", UpperVal - LowerVal));
        }
    }
}

// and then serialize using the JsonConvert class
var obj = new JSObj { Title = "Test", LowerVal = 4, UpperVal = 10 };
var jsonObj = JsonConvert.SerializeObject(obj);
Community
  • 1
  • 1
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60