JSON syntax in C# - 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 + "'}\"" +#",

Related

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

MVC method call working in Fiddler, but not in browser

I am able to get a result back from a method call in Fiddler using the below syntax:
http://localhost:1196/Home/GetSpecificFuelTicketAsync/6460194
Note that as going through Fiddler, my controller breakpoints are hit and I can see where it returns a value coming out of the method.
However, I am not able to get a result back when running from my browser. When it tries to execute the ajax method, the "success" function does not fire and skips to the "error" function where it says it can't find the record.
What am I doing wrong with my ajax call? There is something I am definitely doing wrong in my ajax call. I have verified during debugging, that the variable "ticketNbr" actually contains a value.
Here is my ajax call:
$.ajax({
url: "Home/GetSpecificFuelTicketAsync",
data: "{id:" + ticketNbr + "}",
type: "POST",
dataType: "json",
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});
Here is my Route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is my controller method:
[HttpPost]
public async Task<JsonResult> GetSpecificFuelTicketAsync(int id)
{
try
{
string imageID = await db.GetSpecificFuelTicketAsync(id);
return Json(imageID, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
strRemedyTktResponse = IssueRemedyTicket("Class: FuelTktController" + CrLf + "Method: GetSpecificFuelTicket" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace);
LogMessage.WriteEventLog("Class: FuelTktController" + CrLf + "Method: GetSpecificFuelTicket" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace, "FuelTktController", 1, strRemedyTktResponse);
return null;
}
}
I think it might just be the way you are defining your ajax call.. try this
$.ajax({
url: '#Url.Action("GetSpecificFuelTicketAsync")',
data: "{'id': '" + ticketNbr + "'}",
type: "POST",
contentType: 'application/json; charset=utf-8',
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});
Change this line -
data: "{id:" + ticketNbr + "}",
to this -
data: "id=" + ticketNbr,
or this -
data : {id: ticketNbr} //loose the quotations.
and try again.
With this controller method the next one is even better option -
$.ajax({
url: "Home/GetSpecificFuelTicketAsync/" + ticketNbr,
type: "POST",
dataType: "json",
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});

Post Json data to web methods

I have the following variable that post it normally to the following web method.
data: "{item:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
The web method:
[WebMethod(EnableSession = true)]
public static string GetCart(string item, string step)
{
HttpContext.Current.Session["f"] = item;
HttpContext.Current.Session["l"] = step;
return item;
}
When I try to add the following variable the 3rd variable(mytest) is not posted
data: "{item:" + JSON.stringify(json) + ",mytest:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
The web method
[WebMethod(EnableSession = true)]
public static string GetCart(string item, string step, string mytest)
{
HttpContext.Current.Session["f"] = item;
HttpContext.Current.Session["l"] = step;
HttpContext.Current.Session["mytest"] = mytest;
return item;
}
Edit
And the post statment
$.ajax({
type: 'POST',
url: "mypage.aspx/GetCart",
data: "{item:" + JSON.stringify(json) + ",mytest:" + JSON.stringify(json) + ",step:" + JSON.stringify(john) + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
You need double quotes:
...
data: "{\"item\":" + JSON.stringify(json) + ",\"mytest\":" + JSON.stringify(json) + ",\"step\":" + JSON.stringify(john) + " }"
...
Alternatively, you could stringify once:
...
data: JSON.stringify({item: json, mytest: json, step: john })
...

Message: Invalid JSON primitive: ajax jquery method with Webmethod

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

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