Hi i have a table with following values
Country Count
China 2
India 3
Pakistan 3
i want these in JSON as "China" : 2,"India" : 3,"Pakistan" : 3
I don't want the header Count and Country. I Have tried using ajax and HTTP Handler but no avail
$(document).ready(function () {
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
dataType: 'json',
success: function (data) {
var test = data.Country + data.Count;
alert(test);
},
error: function (data) {
alert("Error");
}
});
});
public void ProcessRequest(HttpContext context)
{
FilterCountry emp = getCounts();
// serialize and send..
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sbJsonResults = new StringBuilder();
serializer.Serialize(emp, sbJsonResults);
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(sbJsonResults.ToString());
}
private FilterCountry getCounts()
{
FilterCountry fc = new FilterCountry();
fc.Country = "PK";
fc.Count = 600;
return fc;
}
I gives me as PK600 but it should give "PK":600 and how to get these values from database right now im trying to get from hard coded values.
var test = data.Country + data.Count;
Try to change to:
var test = data.Country + ':' + data.Count;
If you are using JavaScriptSerializer then it will will serialize the object in to JSon format like "Key":"Value" that is also based on the object you are passing to Serialize method.
Your class "FilterCountry" has two property "Country" and "Count" and assigning values on it.
So it will be serialize like as follows { "Country" : "PK", "Count":600 }
Please go through JSon and serialize examples
Related
I am posting data to a controller stringified by knockout:
var data = ko.toJSON(viewModel);
$.ajax({
type: 'POST',
url: '#Url.Action("Action")',
data: { data: data },
dataType: 'json'
....
})
Then server-side, I try to deserialize the data with JsonConvert.
var viewModel = JsonConvert.DeserializeObject<ViewModel>(data,
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local,
DateFormatHandling = DateFormatHandling.IsoDateFormat
});
This fails if data contains null values (serialized as "NaN"), looking like this:
"MyField":"NaN"
Without null values, it works fine.
I tried adding NullValueHandling = NullValueHandling.Include/Ignore to the serializer settings, both without success.
I got around the problem by adding a small replacer function to the knockout stringifier (as suggested by DavidG - thank you, I should have made this work from the beginning).
var data = ko.toJSON(viewModel, function (key, value) {
if (value == "NaN") {
return;
}
else {
return value;
}
});
I'm trying to code a simple autocomplete using LINQ to entities and Razor (new to c# sharp as well) and i'm having trouble displaying json data in my view.
My controller is as follows:
public ActionResult AutoCompleteCity(string guess)
{
List<City> listData = null;
if (!string.IsNullOrEmpty(guess))
{
listData = db.AutoCompleteCity(guess);
}
return Json(new { Data = listData });
}
AJAX call:
function getCities(input) {
var serviceURL = $("#autocompleteURL").val();
var url =
$.ajax({
type: "POST",
url: serviceURL,
data: {
'guess': input
},
dataType: 'json',
success: function (response) {
if (response.Data != null) {
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
Data = response.Data;
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
});
}
I might be missing a bracket or two :D
Any way when i retrieve records from the database and try to pass JSON values to the view the output is:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
I assume I'm not passing the JSON listData correctly. Any input will be greatly appreciated, thanks!
EDIT: here is a screencap of the values returned by listData in my controller
This is my LINQ query
public List<City> AutoCompleteCity(string guess)
{
using (var context = new Sports.SportsEntities())
{
var query = (from loc in context.city
join prov in context.state on loc.STATE_ID equals prov.STATE_ID
where loc.CITY_DESC.Contains(guess.ToUpper())
select new
{
city = loc.CITY_DESC,
state = prov.STATE_DESC,
});
IEnumerable<City> cityList= from ba in query.AsEnumerable()
select new City(ba.city, ba.state);
return cityList.ToList();
}
}
This error:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
was caused by having declared private attributes in the City Class, or by failing to declare getter/setter methods if said attributes are meant to be private.
I figured that out by looking at the screen capture posted on my question, only displaying the "selected", "text" and "value" properties and not the city and state description in the query results, which was what I needed to display below the textbox input.
This controller method will do the trick:
public JsonResult AutoCompleteCity(string term)
{
List<City> listData = new List<City>();
if (!string.IsNullOrEmpty(term))
{
listData = db.AutoCompleteCity(term);
}
return Json(listData, JsonRequestBehavior.AllowGet);
}
The problem is probably this piece of code in the AJAX call:
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
By doing this you are removing the ul tag from the DOM and therefore cannot add the li elements you are constructing in this piece of code:
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
If you want to clear the list use .empty():
if ($("#targetUL") != undefined) {
$("#targetUL").empty();
}
if you want to return a JSON, change that:
public ActionResult AutoCompleteCity(string guess)
by
public JsonResult AutoCompleteCity(string guess)
and also try that:
Data = JSON.parse(response.Data);
It looks like your method returns a list of City objects, so maybe you need to use the property of that objects to get to the city name, something like this:
$.each(Data, function (i, city) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + city.Name + "</li>"));
});
Here's my controller action
[HttpGet]
public JsonResult GetOrderNum(String input)
{
AEntities db = new AEntities();
var result = from r in db.orders
where r.TrackingNumber.ToString() == input
select new {
r.Status,
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And here I make the AJAX call
var myActionUrl = '#Url.Action("GetTrackingNumber", "ACustomer")';
var trackingInfo = $('#TrackingNumber').val();
$('.Track').click(function () {
$.ajax({
type: "GET",
url: myActionUrl,
data: $('#TrackingNumber').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
alert("Response as JS Object: " + json);
console.log(json);
}
});
the problem is that it wont read the r.TrackingNumber.ToString() as it is system.guid. Any idea how I can resolve this?
At the moment when I run it, I just get an empty array "[]".
There are a number of different ways that a GUID can be represented as a string.
System.Guid.ToString() provides an overload with a format specifier. Select a format specifier that matches the format of the GUID found in input.
UPDATE
'System.String ToString()' method, and this method cannot be translated into a store expression
You will need to instead create a GUID from input:
Guid inputGuid = Guid.Parse(input);
var result = from r in db.orders
where r.TrackingNumber == inputGuid
select new {
r.Status,
};
Change the method public JsonResult GetOrderNum(String input) to read public JsonResult GetOrderNum(Guid input) thus passing the parameter as a GUID. Then there is no need to convert the data store GUID.
function FunctionName(Input) {
$.ajax({
type: 'GET',
url: '/GetOrderNum?Input=' + Input=', // Your URL Here
data: $('#TrackingNumber').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
alert("Response as JS Object: " + json);
console.log(json);
}
});
}
[HttpGet]
public JsonResult GetOrderNum()
{
string input =HttpContext.Current.Request["Input"].ToString();
Guid input= Guid.Parse(input);
AEntities db = new AEntities();
var result = from r in db.orders
where r.TrackingNumber.ToString() == input
select new {
r.Status,
};
return Json(result, JsonRequestBehavior.AllowGet);
}
I have created one string array in jquery of name array[] and pushed values to it.
How can I send this array in query string?
For example window.location.href('ViewData?array');
And how can I get back the array data from query string in jquery itself ?
Please advice?
This is very easy to achieve with jQuery as it has a helper function called param().
var myData = {
name: "John Doe",
age: 23,
children: [{
name: "Jane Doe",
age: 13,
children: []
},
{
name: "John Doe Jr.",
age: 16,
children: []
}
],
}
var p = $.param(myData)
The results:
"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"
You can use it like so:
window.location = "/MyController/MyAction?" + p;
As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?
Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.
$.ajax({
url: "/MyController/MyAction",
data: myData,
dataType: "json",
type: "POST",
success: function(data){
//'data' is your response data from the Action in form of a javascript object
}
})
I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));
Okay I am serializing a bunch of years from a database call into a json object.
This object is the response from the webservice to the first ajax call. My javascript error console throws an error on the line where it is suppose to deserialize it. I am trying to figure out what is wrong.
Update:
This code works, thanks to Jussi Kosunen
$.ajax(
{
type: "POST",
url: "default.aspx/HelloWorld",
dataType: "json",
data: "{name:'" + name + "'}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
//parse the object into something useable.
var stringarray = JSON.parse(msg.d);
//empty the results for next time around.
$('#year').empty();
for (index in stringarray) {
$('#year').append('<option>' + stringarray[index] + "</option>");
alert(stringarray[index]);
}
This is the C# that serialized the list into an json object;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string HelloWorld(string name)
{
string splitme = "USE VCDB SELECT DISTINCT YearID FROM BaseVehicle";
DataTable dt = getDataTable(splitme);
List<string> ids = new List<string>();
foreach (DataRow row in dt.Rows)
{
ids.Add(row.ItemArray[0].ToString());
}
JavaScriptSerializer js = new JavaScriptSerializer();
string x =js.Serialize(ids);
return x;
}
Now when I go into debug. this is the string the C# is returning.
[\"1896\",\"1897\",\"1898\",\"1899\",\"1900\",\"1901\",\"1902\",\"1903\",\"1904\",\"1905\",\"1906\",\"1907\",\"1908\",\"1909\",\"1910\",\"1911\",\"1912\",\"1913\",\"1914\",\"1915\",\"1916\",\"1917\",\"1918\",\"1919\",\"1920\",\"1921\",\"1922\",\"1923\",\"1924\",\"1925\",\"1926\",\"1927\",\"1928\",\"1929\",\"1930\",\"1931\",\"1932\",\"1933\",\"1934\",\"1935\",\"1936\",\"1937\",\"1938\",\"1939\",\"1940\",\"1941\",\"1942\",\"1943\",\"1944\",\"1945\",\"1946\",\"1947\",\"1948\",\"1949\",\"1950\",\"1951\",\"1952\",\"1953\",\"1954\",\"1955\",\"1956\",\"1957\",\"1958\",\"1959\",\"1960\",\"1961\",\"1962\",\"1963\",\"1964\",\"1965\",\"1966\",\"1967\",\"1968\",\"1969\",\"1970\",\"1971\",\"1972\",\"1973\",\"1974\",\"1975\",\"1976\",\"1977\",\"1978\",\"1979\",\"1980\",\"1981\",\"1982\",\"1983\",\"1984\",\"1985\",\"1986\",\"1987\",\"1988\",\"1989\",\"1990\",\"1991\",\"1992\",\"1993\",\"1994\",\"1995\",\"1996\",\"1997\",\"1998\",\"1999\",\"2000\",\"2001\",\"2002\",\"2003\",\"2004\",\"2005\",\"2006\",\"2007\",\"2008\",\"2009\",\"2010\",\"2011\",\"2012\",\"2013\"]
As you're passing dataType: "json" into your $.ajax call, it's parsing your JSON automatically.