I'm trying to get JSON out of a webforms.cs page to .aspx page. It's relatively easy to do with JSONResult in MVC but it seems to be a pain with webforms.
So I have [WebMethod] function in my cs file like below.
This method is returning really weird json.
Fiddler's raw result looks like below.
{"d":"[[{\"name\":\"Label1\",\"y\":28....
Is there something like JsonResult for webforms? I guess since method return is of type string it's messing up the result and I don't know why it's coming up as array inside array and with name d.
I need this in [{name: "Label1", "y":28},{...] format.
How do i get it in this format?
[WebMethod]
public static string GetData()
{
JavaScriptSerializer json = new JavaScriptSerializer();
var myTable= DataTable.AsEnumerable().Where(x => x.Field<int>(1) == 2018)
.Select(x => new[]
{
new { name = "LABEl 1", y = x[2] },
new { name = "Label 2", y = x[3] },
});
String export= json.Serialize(myTable);
return export;
}
You could easily convert it back to json inside success method of your Ajax call using
var obj = JSON.parse(response.d);
Related
I'm parsing a json which has 3 properties that have arrays as values, to my controller. I managed to save the json to a Dictionary, and now i need those 3 arrays to make a query to my database.
The setup is the following
public JsonResult FilterMultiselects(string json)
{
Dictionary<string, string[]> filters = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(json);
string[] lines = filters["lines"];
string[] countries = filters["countries"];
string[] users = filters["users"];
var query = ... //do my query which returns the results i desire
string result = JsonConvert.SerializeObject(query, Formatting.Indented,
new JsonSerializerSettings {
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
return Json(result, JsonRequestBehavior.AllowGet);
}
The problem im having is that when i get to the part in which i initialize those 3 arrays only the second one(countries) exists. The other two dont even create which makes no sense to me. Even thought i have not worked with Dictionaries(hashes) too much in C# it looks good.
Could anyone help me with what am i missing?
The json im parsing has the following look:
{
lines: ["line 1", "line 2"]
countries: ["England"]
users: []
}
The string my controller receives is:
"{\"lines\":[\"line 1\",\"line 2\"],\"countries\":[\"England\"],\"users\":[]}"
The dictionary gets created and has 3 keys that have the correct arrays as values.
I am writing a backend for SlickGrid. I have an AJAX call that loads the column definitions from my MVC Controller. The controller looks like this:
Public ActionResult GetColumns(...){
List<object> columns;
foreach(var col in MyColumns){
columns.Add(new { id = col.id, name = col.name, width = col.width});
}
return Json(new { columns = columns });
}
One of the column attributes that slickgrid accepts is formatter, which takes a js function name.
Unfortunately, MVC puts that name in double quotes. I need to figure out if there is a way to serialize just that one field without quotes.
eg (this is what I want)
[{"id":1,"Name":"FirstName","width":50,"formatter":NameFormater},...]
vs (ths is what I am getting now)
[{"id":1,"Name":"FirstName","width":50,"formatter":"NameFormater"},...]
I know this isn't proper JSON Format to pass JS Code in it(Proper JS Format though). But I have a valid use case here and am trying not to add too much complexity.
You could wrap the word NameFormater with special characters such as
[{"id":1,"Name":"FirstName","width":50,"formatter":"#NameFormater#"},...]
and when you get your results back, if you are using javascript
function(result){
result = result .replace(/"#/g, "");
result = result .replace(/#"/g, "");
// result now = [{"id":1,"Name":"FirstName","width":50,"formatter":NameFormater},...]
// ...Pass result to SlickGrid
}
I have json string which will pass to the webservice to perform some action on it. My json string will b like this example:
{"ID":"2","Name":"Tom","data":"[22.3,23.4,21.5]"}
I want to validate the json string if I remove the , (coma):
{"ID":"2""Name":"Tom""data":"[22.3,23.4,21.5]"}
From the json string so its return error message json is not in the correct format.
JSON.net and JSONSharp allow you to parse JSON into an object and will have the ability to validate or at least catch an exception on errors
Try
var dynamicObject = Json.Decode(jsonString);
And see if it raises an error.
You may need to install the DLL for this separately. I believe it is in the MVC library download.
http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx
Maybe you can try creating the JSON with the function ToJSON()
List<MyObject> people = new List<MyObject>{
new MyObject{ID = 1, Name= "Tom", Data= "[22.3,23.4,21.5]"},
new Person{ID = 2, Name= "Tome", LastName = ""[22.3,23.4,21.5]"}
};
string jsonString = people.ToJSON();
And if you with have the string as JSON you can do something like:
JsonConvert.SerializeObject(jsonString ).Dump();
Or using the Networking JSON:
http://james.newtonking.com/json
A working code snippet
public bool isValidJSON(String json) {
try {
JToken token = JObject.Parse(json);
return true;
}
catch(Exception ex){
return false;
}
}
Source
The below code is returning [object Object] not a string. How can I get it to return the correct string representation? I am using ASP.NET MVC4 C#.
public JsonResult Names(string name)
{
var a = db.NamesToGet.Select(e => new
{
name = e.Names
});
return Json(a, JsonRequestBehavior.AllowGet);
}
try
var a = db.NamesToGet.Select(e=>e.Names);
Access it with data.name or substitute data to your json variable name.
$.get("/Controller/GetName", function(data) {
alert(data.name);
//or alert(data[0].name);
});
I am intentionally trying NOT to use a binding in the controller parameter, so I have a controller that looks like:
[HttpPost]
public ActionResult UntypedForm(String serializedformdata)
{
//// ...
}
When I post serialized JSON form elements to the controller with the below code:
var formelements = $('#form').serializeArray();
$.post(url, formelements, function (data) {
}, "json").error(function () {
alert("Error posting to " + url);
});
I get a NULL value for String serializedformdata on my controller. However, when I replace String serializedformdata with a strongly-typed object, binding works properly as expected.
The whole point of my controller is generic JSON posts, where I will create a BSON document to place into a Mongo database. SO....I intentionally DO NOT want model binding and I want the serialized string as pamameter. Why is my serializedformdata string null when I post?
Note - I also tried to bind to Dictionary with
public ActionResult UntypedForm(Dictionary<string,string> serializedformdata)
{
//// ...
}
but serializedformdata is still null.
The function serializeArray creates a Javascript object with the form's key/value pairs. You don't want that, you want a single key/value with serializedformdata = (JSON string). Ie, like this;
var formelements = { serializedformdata: JSON.stringify($('#form').serializeArray()) };
This passes the raw JSON string to the controller's parameter. You can use the JavaScriptSerializer to get the object on the server:
var obj = (List<Dictionary<string,string>>)new JavaScriptSerializer().Deserialize(serializedformdata, typeof(List<Dictionary<string,string>>));
Dictionary<string,string> dict = obj.First();
string someval = dict["somekey"];