1

I have a C# class which contains a property of Dictionary

I have a web-page which contains a list of items i need to cast into this dictionary.

My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.

JsonConvert.Deserialise is expecting JSON in the following format:

  "MyVariableName":{
      "Item 1":true,
      "Item 2":true
   }

I need to know how i can construct this object in JavaScript.

So far, i have tried this without luck:

    var items = [];

    var v = $('#Items :input');
    $.each(v, function(key, val) {

        items.push({
            key: val.value,
            value: val.checked
        });
    });

    JSON.stringify(v, null, 2);

But this returns a json converted value of:

"MyVariableName": [
    {
      "key": "Item 1",
      "value": true
    },
    {
      "key": "Item 2",
      "value": true
    }]

Which in turn does not de-serialize to my dictionary.

Thanks

1
  • 1
    your target "object" is missing top level brackets. Aside from that, your target format is NOT an array, therefore using var items = [] and .push aren't going to do what you want. Commented Jun 20, 2013 at 14:28

2 Answers 2

1

Don't make an array; make an object:

var items = {};
$('#Items :input').each(function(i, val) {
    items[val.value] = val.checked;
});
Sign up to request clarification or add additional context in comments.

Comments

0

You have to use javascript serialization

One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.

And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.

 var jSerializer = new JavaScriptSerializer();
 var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);

Comments

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.