Passing json object to webmethod via jquery ajax - c#

I am trying to pass a json object to my .net webmethod.
Here is my C#:
[WebMethod]
public static string Guncelle(string personel)
{
return "It came.";
}
And my jquery ajax:
var saveData = {};
saveData.Isim = isim;
saveData.Soyad = soyisim;
saveData.Firma = firma;
.
.
.
var result = JSON.stringify({ personel: saveData });
$.ajax({
type: "POST",
url: "Personeller.aspx/Guncelle",
data: result,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
})
When I run code, it returns 'undefined' with alert. What is the correct way of passing json object to C# Webmethod ? I tried other examples for passing an object but none of them worked for me.

try this: data: "{personel:'" + saveData+ "'}"

Related

ASP.NET C# Ajax Call Error

I'm going straight to the point here.
I'm trying to get the value pass from my ajax to controller and console.log the value. however, when I try to console.log the value it gives me error 500..
here's my code:
I've been doing ajax on php for a long time.. however, I'm still new to asp.net C# mvc so please bear with me.
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
CONTROLLER:
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
here's the error I don't know what's wrong with my controller though.
POST http://localhost:43969/Property/GetCities 500 (Internal Server
Error)
if using contentType: 'application/json; charset=utf-8' then use JSON.stringify to convert the data being sent to a JSON string.
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
As mentioned in the comments by #StephenMuecke
It does not need to be stringified if contentType: 'application/json; charset=utf-8', is removed (so that it uses the default application/x-www-form-urlencoded; charset=UTF-8').
you can add error function to check for possible error on your ajax.
Ex.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

Object obect error on jquery ajax request on dropdown change?

I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.

Jquery to ashx not working event not fired

I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});

jQuery.ajax "data" parameter syntax

I am trying to pass the contents of a javascript variable to the server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code:
(Client)
function expand(checkbox)
{
var selectedrow = checkbox.parentNode.parentNode;
var rowindex = selectedrow.rowIndex;
var parent = document.getElementById("parentTable");
var NextRow = parent.rows[rowindex + 1];
var cols = selectedrow.cells[1];
var ID = cols.firstElementChild.attributes.value;
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: "{sendData: ID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
NextRow.style.visibility = "visible";
}
(Server)
[WebMethod]
public static string childBind(string sendData)
{
return String.Format("Hello");
}
Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?
You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.
Try this
data: { sendData: ID }
You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: {sendData: ID},
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
You can also write this, if you want to send JSON:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: $.getJSON({sendData: ID}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) { alert("successful!" + result.d); }
})
Since you are using jQuery run these tests for the answer:
var ID = 45;
var x = "{sendData: ID}";
alert(jQuery.isPlainObject(x)); // false
var y = { sendData: ID};
alert(jQuery.isPlainObject(y)); // true
Here is the jsFiddle:
http://jsfiddle.net/3ugKE/
You are passing in 'ID' as a string rather than a variable.
All you need to do is remove the quotes around your data object.
Further reading on JSON and javascript objects:
http://www.json.org/
http://www.w3schools.com/js/js_objects.asp
you can use this code :
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: JSON.stringify({sendData: ID}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})

Categories