简体   繁体   English

将字典从 Ajax 传递到 C# 代码隐藏

[英]Pass Dictionary From Ajax to C# Codebehind

I am using ASP.Net and jquery/ajax我正在使用 ASP.Net 和 jquery/ajax

I have the following script in jquery:我在 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谢谢

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);
    }
}

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属性修饰您的方法(在代码后面)

[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 然后确保使用jquery将json对象发布到正确的URL ...例如... PageName.aspx / AddProductToDb

That's all you need if you are using page methods 如果您使用页面方法,那就是您所需要的

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: 我使用了Damith的答案基础来形成我将要传递的参数,并通过以下方式传递它来使其工作:

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: 然后在MVC代码上我使用以下签名的方法:

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. 通过这两件事,我能够让方法检测作为Dictionary<string,string>传递的信息Dictionary<string,string>同时我能够传递其他参数。 Hopefully this will resolve your issue. 希望这将解决您的问题。

I believe you need to set traditional to true so it will serialize properly 我相信你需要将传统设置为true,以便正确序列化

$.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);
   }
}

Please refer below code. 请参考以下代码。 Make sure your method "AddProductToDB" has HttpPost attribute and identical/same name of the parameter in this case "sizeList" . 确保您的方法“AddProductToDB”具有HttpPost属性和参数的相同/相同名称,在本例中为“sizeList”

C# / MVC / Back End Side : C#/ MVC /后端:

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

    //Business logic or Data

}

Javascript / jQuery / Client Side: Javascript / jQuery /客户端:

And Enter the URL where you this function/method AddProductToDB. 并输入此函数/方法AddProductToDB的URL

For example "YourController/AddProductToDB". 例如“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>

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM