Jean Claude Abela
Jean Claude Abela

Reputation: 907

Pass Dictionary From Ajax to C# Codebehind

I am using ASP.Net and jquery/ajax

I have the following script in jquery:

var sizes = [];
sizes.push({ key: "1", value: "3"});
$.ajax({
    type: "POST",
    url: pageUrl,
    data: '{"sizeList":' + sizes + '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Status: " + textStatus); alert("Error: " + errorThrown);
    }
}

This is the codebehind:

public static void AddProductToDB(Dictionary<String, String> sizeList)

Can someone please tell me what I am doing wrong as I have tried everything I could think of. Thanks

Upvotes: 1

Views: 7384

Answers (6)

M Safari
M Safari

Reputation: 1

you can use this:

var param = {
    '1': '3'
};

$.ajax({
    type: "POST",
    url: pageUrl,
    data: JSON.stringify({sizeList: param}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
       alert("Status: " + textStatus);
    }
}

then you can read it from dictionary variable with this:

 public static void AddProductToDB(Dictionary<String, String> sizeList) {
     sizeList["1"]; // return "3"
 }

Upvotes: 0

vishpatel73
vishpatel73

Reputation: 317

Please refer below code. Make sure your method "AddProductToDB" has HttpPost attribute and identical/same name of the parameter in this case "sizeList".

C# / MVC / Back End Side :

[HttpPost]
public static void AddProductToDB(Dictionary<String, String> sizeList)
{

    //Business logic or Data

}

Javascript / jQuery / Client Side:

And Enter the URL where you this function/method AddProductToDB.

For example "YourController/AddProductToDB".

<script type="text/javascript">

    var sizes = [];
    sizes.push({ "Key": "key1", "Value": "value1" });
    sizes.push({ "Key": "key2", "Value": "value2" });
    sizes.push({ "Key": "key3", "Value": "value3" });
    $.ajax({
        type: "POST",
        url: '/YourController/AddProductToDB',
        data: JSON.stringify({
            sizeList: sizes
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
        alert("success");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Status: " + textStatus); alert("Error: " + errorThrown);
        }
    });

</script>

Upvotes: 0

johnny 5
johnny 5

Reputation: 21015

I believe you need to set traditional to true so it will serialize properly

$.ajax({
    type: "POST",
    url: pageUrl,
    traditional: true,
    data: '{"sizeList":' + sizes + '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Status: " + textStatus); alert("Error: " + errorThrown);
   }
}

Upvotes: 0

Jambris
Jambris

Reputation: 56

I am looking at this two years after it got posted but hopefully it will help someone if they stumble upon this post. I used the base of Damith's answer to form the parametes I was going to pass and got it to work by passing them the following way:

var param = {
    'filters[0].Key': '1',
    'filters[0].Value': 'test',
    'filters[1].Key': '2',
    'filters[1].Value': 'test',
    id: 1,
    width: 150,
    height: 150,
};

Then on the MVC code I had my method with the following signature:

public async Task<ActionResult> IndexPartial(int id = -1, int? width = null, int? height = null, Dictionary<string, string> filters = null)

With these two things I was able to have the method detect the information passed as a Dictionary<string,string> and at the same time I was able to pass in additional parameters. Hopefully this will resolve your issue.

Upvotes: 2

Damith
Damith

Reputation: 63105

var param = {
    '[0].Key': '1', 
    '[0].Value': '3'
};

$.ajax({
    type: "POST",
    url: pageUrl,
    data: param 
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("success");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Status: " + textStatus); alert("Error: " + errorThrown);
    }
}

Upvotes: 2

Leo
Leo

Reputation: 14850

Looks like you are trying to use a page method. If so, you need to decorate your method (in code behind) with the WebMethod attribute

[WebMethod]
public static void AddProductToDb(Dictionary <string, string> sizelist){}

Then make sure you are posting the json object with jquery to the correct url...for example...PageName.aspx/AddProductToDb

That's all you need if you are using page methods

Upvotes: 1

Related Questions