Message: Invalid JSON primitive: ajax jquery method with Webmethod - c#

I am using Data value as object literal, instead of concatenating a String as explained in this answer
My code is the following:
$.ajax({
url: "../Member/Home.aspx/SaveClient",
type: "POST",
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
},
success: function(response) {
if (response.d != "") {
}
},
error: function(response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
})
and my webmethod is like this :
[WebMethod]
public static string SaveClient(string projectSoid, string startDate,
string endDate, string clientManager)
{
...
}
But I get the following error:
Message: Invalid JSON primitive: projectSoid

With your contentType: 'application/json; charset=utf-8' you are claiming that you will send JSON but currently your data property is not holding JSON.
You need to transform your data to JSON with the JSON.stringify method:
So change your data property to:
data: JSON.stringify({
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
}),
You should note that the JSON.stringify method is not natively supported in older browsers so you may need to provide an implementation with using one of the various libraries like:
Douglas Crockford's JSON2 library.

Javascript at Client side
var items = [{ projectSoid: ProjectId, startDate: StartDate, endDate: EndDate, clientManager: ClientManager }];
$.ajax({
url: '"../Member/Home.aspx/SaveClient',
type: "POST",
data: JSON.stringify({ items: items }),
//data: JSON.stringify("{DocKey : '" + DocKey + "',highlightText: '" + JSON.stringify(text) + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}"),
//data: "{DocKey\":\""+ DocKey+"\",\"highlightText\":\""+ text +"\",\"pageNo\":\""+pgNo+"\",\"left\":\""+left+"\",\"top\":\""+top+",\"width\":\""+width+"\",\"height\":\""+ height +"}}",
// data: "{DocKey : '" + DocKey + "',highlightText: '" + text + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("Save data Successfully");
},
failure: function (msg) { alert("Sorry!!! "); evt.obj.deleteObject(); },
async: false
});
Web Method at Code behind
[WebMethod]
public static string SaveClient(object items) {
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
Dictionary<string, object> dic = (Dictionary<string, object>)lstItems[0];
}

Related

JSON-data to WebMethod using jQuery returning errors

I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}

Strange json response bact to jQuery [duplicate]

So here is my problem. I'm using Jquery's $.ajax to pass back a series of values to a web method. The web method takes the values, creates an object and then sends it back as json to the calling page. Once I get the response back I am unable to access the response and display it's values.
Can anyone explain what I need to do to make this work?
The jquery script:
$(document).ready(function() {
$("#create").click(function() {
var name = $('#name').val();
var company = $('#company').val();
var location = $('#location').val();
var phonenumber = $('#phonenumber').val();
var country = $('#country').val();
$.ajax({
type: "POST",
url: "WebService.asmx/MakeEmployee",
data: "{name:'" + name +
"',company:'" + company +
"',location:'" + location +
"',phonenumber:'" + phonenumber +
"',country:'" + country +
"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg.d);
}
});
});
function AjaxSucceeded(data) {
//var item = jQuery.parseJSON(data) // this doesn't work for me.
$("#response").html(
"<ul><li> " + data.Name +
"</li><li> " + data.Company +
"</li><li> " + data.Address +
"</li><li> " + data.Phone +
"</li><li> " + data.Country +
"</ul> "
);
};
});
The web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MakeEmployee(string name, string company,
string location, string phoneNumber, string country)
{
Employee e = new Employee(name, company, location, phoneNumber, country);
return new JavaScriptSerializer().Serialize(e);
}
And the response that I'm getting back:
{"d":"\"Name\":\"bob\",
\"Company\":\"google\",
\"Address\":\"home\",
\"Phone\":\"123\",
\"Country\":\"usa\"}"}
This is what I think I should be getting back:
{"Name":"bob",
"Company":"google",
"Address":"home",
"Phone":"123",
"Country":"usa"}
The error I get once the pages renders again is this:
•undefined
•undefined
•undefined
•undefined
•undefined
Your response will already be parsed as JSON, so it's already an object...no need to parse it again just use it directly, like this:
function AjaxSucceeded(data) {
$("#response").html(
"<ul><li> " + data.Name +
"</li><li> " + data.Company +
"</li><li> " + data.Address +
"</li><li> " + data.Phone +
"</li><li> " + data.Country +
"</ul> "
);
}
The { d: ... } wrapper is added by ASP.Net, that's normal behavior. After that your issue is the element not returned correctly, you need to return an object not a string from ASP.Net, preferably this:
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(string name, string company,
string location, string phoneNumber, string country) {
return new Employee(name, company, location, phoneNumber, country);
}
...where Employee has the properties you want on the JavaScript side. Let ASP.Net handle the serialization here instead of doing it directly, you'll get a cleaner response overall.
Try using this ajax initaliazer function for asp.net ajax. It sets most defaults so you only have to supply url/params
Just call in your document.ready() function first, and then your calls.
function jqueryInit() {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function (data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
}
Start by cleaning your service method. You really don't need this constructor and all those properties. You already have an Employee type, so use it:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(Employee e)
{
// Maybe do something more useful here with this employee
// like raise his salary
return e;
}
And then clean your javascript:
$.ajax({
type: 'POST',
url: 'WebService.asmx/MakeEmployee',
data: JSON.stringify({
// All those correspond to Employee properties you would like to pass
Name: $('#name').val(),
Company: $('#company').val(),
Location: $('#location').val(),
PhoneNumber: $('#phonenumber').val(),
Country: $('#country').val()
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// msg.d is gonna be the returned employee
AjaxSucceeded(msg.d);
}
});

JSON syntax in C#

I have written the following Javascript but get the error 'Invalid JSON primitive: strSeason'. The rest of the syntax seems fine but I can't seem to get the 'data' parameter right. Can anybody help me with the syntax?
TagBuilder script = new TagBuilder("script");
script.Attributes.Add("type", "text/javascript");
script.Attributes.Add("language", "javascript");
// ReSharper disable LocalizableElement
script.InnerHtml = #"
$.ajax({
type: 'POST',
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
url: '/en-US/" + areaName + '/' + controllerName + '/' + actionName + #"',
data: " + "{strSeason:'" + season + "', strTeam:'" + team + #"'},
beforeSend: function(xhr){
$(this).addClass('ajaxRefreshing');
xhr.setRequestHeader('X-Client', 'jQuery');
},
success: function(html){
$(this).html(html);
},
complete: function(){
$(this).removeClass('ajaxRefreshing');
}
});
";
wrap the names in quotes
data: " + "{'strSeason':'" + season + "', 'strTeam':'" + team + #"'},
EDIT: You may just need to send the JSON string so wrap entire string in quotes.
data: " + "\"{'strSeason':'" + season + "', 'strTeam':'" + team + "'}\"" +#",

How to pass parameter(email ID) to a c# function from Jquery Ajax call?

I am trying to call a Web Method of service from a Jquery Ajax call.
Method accepts 3 parameter from the front end and search for the record in the DB.
I am not able to concatinate those 3 parameter properly in the Ajax call :
The Web Method is :
public bool FindRecord(string Fname, string Lname, string Email)
{
string SQL = "SELECT * FROM contactsSource WHERE (first_name ='" + Fname + "') AND (last_name = '" + Lname + "') AND (email_address_work = '" + Email +"')";
OleDbDataReader reader = DataAccess.GetData(SQL);
if (reader.HasRows)
{
return true;
}
else
{
return false;
}
}
and the Ajax call I am trying is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
var Fname = $('#Fname').val();
var Lname = $('#Lname').val();
var email = $('#Email').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":' + email + '}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
//$('.secondary').show(500);
});
});
</script>
But I am keep on getting 500 Internal Server error :
{"Message":"Invalid JSON primitive: (Email ID that I am passing).","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
Your email parameter should be enclosed in double quotes, otherwise it will not be parsed properly as a JSON string value. The corrected syntax should be:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":"' + email + '"}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
You are constructing your data object wrong. Do this instead:
data: {Fname: Fname, Lname: Lname, Email: Email }
No need for quotes..
Try:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {Fname: Fname, Lname: Lname, Email: email},
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});

Passing parameter to controller function from jQuery function '$.ajax'

I am using ASPNET MVC 2.0. I'm trying to pass a value from View to Controller function using jquery function .ajax. My jquery function is:
$(document).ready(function() {
$("#Search").click(function(event) {
var searchString = $("#TraderSearch").val();
$.ajax({
type: 'POST',
url: '/Build/SearchTrader',
data: "{strData : '" + searchString + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(ResultList) {
var contents = "";
var count = 0;
$(ResultList).each(function() {
contents = contents + '<tr><td>' + ResultList[count].Name + '</td><td>' + ResultList[count].Value +
'</td><td><a class="edit"><img src="../../html/images/Edit.gif" width="14" height="14" alt="edit" /></a></td></tr>';
count = count + 1;
});
$("#SerachResultList").append(contents);
alert("{strData : '" + searchString + "' }");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + "\n" + errorThrown);
}
});
});
});
And my Controller function is as follows:
public ActionResult SearchTrader(string strData)
{
//Function to search DB based on the string passed
return Json(lstDictObject);
}
My problem is that, I am not able to get the value in my controller. I'm getting strData as 'null'. I think there is somme mistake in the way i'm trying to pass the value? Can anyone correct me?
Thanks in Advance,
Vipin Menon
try this:
data: "strData = " + searchstring
I believe the following should work:
data: { strData: searchstring }
Quotes caused the same issue in the script I just tested.
You also need to check the spelling on your "#SerachResultList" if this is your actual code.

Categories