Pass Dictionary From Ajax to C# Codebehind - c#

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

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

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.

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

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

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>

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"
}

Related

Ajax post with ASP.NET Webforms

I want to post data to server with ajax call but i am getting an error.
var userdata = {};
userdata["Name"] = "Saran";
var DTO = { 'userdata': userdata };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
I have created a function in Default.aspx.cs and tried to access that function with the above call.
[WebMethod]
public static string update(string userdata)
{
return "Posted";
}
Error :
POST http://localhost:33762/Default.aspx/update 401 Unauthorized 52ms
Message "Authentication failed." StackTrace null ExceptionType
"System.InvalidOperationException"
Firstly, you have to set/update to settings.AutoRedirectMode = RedirectMode.Off; in App_Start/RouteConfig.cs.
Secondly, your ajax payload is not structured properly to make the appropriate call to the update method. See updates below:
var DTO = { 'userdata': 'Saran' };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result.d);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()

Asp.net Post json

login.aspx.cs
[System.Web.Services.WebMethod]
public static string jQueryPageMethod(string name)
{
return "<h3>jQuery - PageMethod </h3>result" + name;
}
JS/Jquery:
If i run below method it works.
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":"exampleValue" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
If i run below method it does not work.
var somevalue = "Value";
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":' + somevalue + ' }', // Problem here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
Where i miss in second example in part of data ?
Your data should not be formatted as a string, but rather as a javascript object like this:
data: { "name": somevalue }, // No Problem here :)
Try this data: '{"queryname":"' + queryname + '"}'

ajax GET works, POST gives 400 error

GetData(...) method was OK, but SetSimple(...) method throwing error 400.
Javascript:
$.ajax(url,
{
type: action,
timeout: 3000,
data: { value: 123 },
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
C#:
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetData(int value);
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
string SetSimple(int value);
To run/test it I have the service opened in a browser, then my test page with the javascript in another browser. (And dataType: "json" doesn't seem to help.)
And the fiddler response shows "The server encountered an error processing the request. See server logs for more details", but I don't see anything in the Event Logs. Anyone see if/what I'm doing wrong?
You should be transform your JavaScript object into string.
JSON.stringify(data)
Then on your example
$.ajax (url,
{
type: action,
timeout: 3000,
data: JSON.stringify({ value: 123 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
Your ajax request is setting the "data" property to { value: 123 }. You need to pass the appropriate object to the SetObject method which is CompositeType. The ajax request looks like you're using it as a utility function so just pass data as a parameter so the ajax request would be:
var makeAjaxCall = function(url, action, data) {
$.ajax(url,
{
type: action,
timeout: 3000,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
}

Access C# method using ajax in asp.net?

Below are both my C# and
JavaScript code, I can access this method but I'm not getting the expected output
from "success":
success: function( msg ){
alert( msg.d );
}
Instead it returns [object object]
Javascript:
$.ajax({
type: "POST",
url: "Home.aspx/UpdateSelectionStatus,
data: '{id_ver: "' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg){alert(msg.d);},
failure: function(){ }
});
C#:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string UpdateSelectionStatus(string id_ver){
return "success" + id_ver;
}
That is the bug:
alert(msg.d);
just use msg directly:
success: function (msg) {alert(msg); },
You returned a simple string, not a complex type, so you haven't got any property like "d".
Please try below code: it is working at my end.
var vid = 10;
$.ajax({
type: "POST",
url: "/Home.aspx/UpdateSelectionStatus",
data: "{id_ver:'" + + vid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
success: function( msg ){
alert( msg.d.toString());
}

Storing data Object coming from a response of jQuery ajax call

I am calling a web method from asp.net 1.1 site and getting a response.
I use this object to populate some data, Now I want to store this object so that I can also save this data in database while saving click event.
How can I achieve this.
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (**msg**) {
// STORE THIS msg object.
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
// STORE THIS msg object.
//if hidden field has id 'name'
$('#name').val(data.name);//if json object contains a key 'name'
//if hidden field has class name
$('.name').val(data.name);
//if hidden field name is name <input type="text" name="name" />
$(document).filter(':[name=name]').val(data.name)
//do the same for all elements to save
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, jqXHR){
// STORE THIS msg object.
/* now you can store data object to where you want to store.*/
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});

Categories