I have a Json which is converted to string and then writted in DataBase
function UpdateFilter() {
var filterOption = {
"filterTarget": "Books",
"filters": [
{ "cancelled": $("#showCancelledFilter").is(':checked') },
{ "completed": $("#showAllFilter").is(':checked') }
],
"page": page,
"sorting": sorting
};
var url = "Library/Books/UpdateFilter";
$.post(url, { pageFilters: JSON.stringify(filterOption) }, function (data) { });
}
Up until this point everything seems to be fine.
Issue starts when I am trying to get json from string:
var data = JObject.Parse(jsonString);
return Json(data, JsonRequestBehavior.AllowGet);
Seems fine BUT in:
$.get('Library/Books/GetPageFilters', null, function(data) {
filterOption = data;
}, "json");
I have received a object with 4 arrays (each on each json property, and each array has empty array inside it).
I assume that I am lacking something in converting string to json, but I can't get it.
What am I missing?
I gess your problem situated where you using $.get() jquery method. From documentation of $.get():
dataType Type: String The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, or html).
Seem like Intelligent Guess can't understand what was come from server.
Try $.getJSON() insted.
Related
I'm trying to integrate BlueImp jQuery file upload component into my ASP.NET 4 website. I have the file upload working and writing to disk, but the component requires that I return a JSON object from the server as confirmation of success, in a particular format:
{"files": [
{
"name": "picture1.jpg",
"size": 902604,
"url": "http:\/\/example.org\/files\/picture1.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
"deleteType": "DELETE"
},
{
"name": "picture2.jpg",
"size": 841946,
"url": "http:\/\/example.org\/files\/picture2.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
"deleteType": "DELETE"
}
]}
I'd like to use the JsonResultClass to return this object in my C#, but I'm not sure how to format the response correctly. I can probably do something like this:
var uploadedFiles = new List<object>();
uploadedFiles.Add(new { name = "picture1.jpg", size = 902604, url = "http://example.org/files/picture1.jpg", thumbnailUrl = "http://example.org/files/thumbnail/picture1.jpg", deleteUrl ="http://example.org/files/picture1.jpg", deleteType = "DELETE" });
uploadedFiles.Add(new { name = "picture2.jpg", size = 902604, url = "http://example.org/files/picture1.jpg", thumbnailUrl = "http://example.org/files/thumbnail/picture1.jpg", deleteUrl ="http://example.org/files/picture1.jpg", deleteType = "DELETE" });
return Json(uploadedFiles);
...but then I'm not sure how to wrap this in the outer 'files' object.
Can anyone point me (a .NET novice trying to learn!) in the right direction here. I've looked at the MSDN documentation but it doesn't go into detail about formatting or constructing more complex JSON objects.
Many thanks.
Replace:
return Json(uploadedFiles);
with:
return Json(new {files = uploadedFiles});
to create a new anonymous type with property "files", which has your original list as a value.
I am trying to parse a JSON object passed from a WCF Service, here is the Response the service gives
[
{
"Caption": "Hello",
"CityState": "Seattle",
"URL": "Test"
},
{
"Caption": "World",
"CityState": "Chicago",
"URL": "Test"
},
{
"Caption": "Hello",
"CityState": "New York",
"URL": "Test"
}
]
Here is the WCF Code to create the object
///Custom Object has 3 string properties
List<OW_CompanyACSearch> search = new List<OW_CompanyACSearch>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<OW_CompanyACSearch>));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, search);
return Encoding.Default.GetString(stream.ToArray());
}
and here is the JQuery that I am trying to make work
source: function (request, response) {
j$.ajax({
url:"testservice.svc",
dataType: "json",
data: {
Search: request.term
},
success: function (data) {
response(j$.map(data, function (item) {
return {
label: item.Caption,
value: item.Caption,
URL: item.URL,
CityState: item.CityState
}
}));
}
});
}
The issue that I am having is that when I fall into the return to parse the members on the object, none of the properties are defined. If I drill down into the object, it seems that it is treating object as one long string, so index[0] would be "[" and so on.
I have read all over and I have tried every option that I have seen and I still get this issue. I am not sure if I am serializing or parsing incorrectly, but any help would be appreciated.
Also, not sure if it matters, but the binding on the WCF is webHttpBinding
Wow this was awesome, come to find out that data was just a wrapper for the JSON object, and there was a property named "d" that was the actual object.
So this
data = j$.parseJSON(data.d);
filled data with the object, and I could move forward.
The data object should already be a variable array that contains your data at the properties as named by the JSON. You should be able to do something like this:
source: function (request, response) {
j$.ajax({
url:"testservice.svc",
dataType: "json",
data: {
Search: request.term
},
success: function (data) {
alert(data[0].Caption);
}
});
}
To verify the object structure.
I have a C#.net method as given below
public string jsonTest()
{
List<string> list = new List<string>();
list.Add("aa");
list.Add("bb");
list.Add("cc");
string output = JsonConvert.SerializeObject(list);
return output;
}
Here eventhough Im creating a Json object by using JsonConvert.SerializeObject I am getting a string (since return type is string).
Can I do like below by using a return type JsonResult (or somthing like that) something like what we can do in MVC?
return Json(new { data = list }, JsonRequestBehavior.AllowGet);
Is it possible to create a Json data in asp.net?
In client side I'm using an ajax call to get data from jsonTest().
$.ajax({
type: 'GET',
url: "test.aspx", //In test.aspx pageload calling jsonTest()
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
When I'm giving dataType: 'json', it will go to error part (Since the ajax expects json data but it gets string). Thats why I want to parse it as a json object in server side.
If ASP.NET,
string output = JsonConvert.SerializeObject(list);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(output);
Response.End();
There is nothing called a JSON object. The SerializeObject method returns a string because JSON is nothing more than a string value which follows specific rules.
To return JSON to the browser all you need to do is:
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonTest());
Response.End();
I'm going to assume you're trying to create a WebMethod for consumption by a JavaScript XHR call or similiar:
ASP.NET will auto-serialize to JSON for POST requests only (using ASMX or so called "Page Methods"). WCF and WebAPI do not require the POST method, but do require some configuration.
[WebMethod]
public static List<Task> TasksGet(string projectId) {
return MyNamespace.Tasks.GetForProject(projectId);
}
The result your JS call sees would be something like:
{"d": [{
"__type": "MyNamespace.Task",
"id": 1,
"description": "This is my first task"
}, {
"__type": "MyNamespace.Task",
"id": 2,
"description": "This is my second task"
}, {
....etc etc
}
]}
No need to mess around w/ the JsonSerializer class directly.
Also make sure your request headers are set correctly:
Content-Accept: application/json;charset=UTF8
Json is just string data. It is how that string is interpreted. So the fact that it is returning a string is correct. You mentioned ASP.Net. Are you using ASP.Net webforms and looking for a way to return that JSON to the front side?
Im trying to return a Json result from my controller and populate a selectlist using jQuery.
But the code dont even hit the Json method in my controller.
My selectlist
<select id="MyList"></select>
My javascript
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("#Url.Action("GetProductJson", "Product")", null, function (data) {
$("#MyList").addItems(data);
});
});
$.fn.addItems = function (data) {
return this.each(function () {
var list = this;
$.each(data, function (index, itemData) {
var option = new Option(itemData.Text, itemData.Value);
list.add(option);
});
});
};
</script>
My Json method in ProductController
[HttpGet]
public JsonResult GetProductJson()
{
var list = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Aron" },
new SelectListItem { Value = "2", Text = "Bob" },
new SelectListItem { Value = "3", Text = "Charlie" },
new SelectListItem { Value = "4", Text = "David" }
};
return Json(list);
}
You should enable JSON for GET requests which is disabled by default. This happens by passing a second argument to the Json method:
return Json(list, JsonRequestBehavior.AllowGet);
Now go ahead and install FireBug. If you had done that prior to posting this question on StackOverflow you could have inspected the AJAX request in your browser and could have seen that the server returns 500 status code and when you inspected the response you would have seen the exact error message and not only that - you would also have seen a suggestion on how to fix it. The suggestion is basically what I posted here in my answer. Thus you wouldn't even had the need to post your question as you would be able to solve it by yourself. I cannot possibly imagine people doing web development without a tool such as FireBug or Chrome Developer Tools. It's like trying to build a house with your own bare hands and without any tools.
you need to add JsonRequestBehavior.AllowGet in your json method
from Phil haack post JsonHijacking
By default, the ASP.NET MVC framework does not allow you to respond to
an HTTP GET request with a JSON payload. If you need to send JSON in
response to a GET, you'll need to explicitly allow the behavior by
using JsonRequestBehavior.AllowGet as the second parameter to the Json
method. However, there is a chance a malicious user can gain access to
the JSON payload through a process known as JSON Hijacking. You do not
want to return sensitive information using JSON in a GET request.
Im trying to hook myself up to a smaller website im a member in.
It has some kind of chat board based on xml which i parse and do statistics on etc.
Now i want to be able to post short summarys using their own options for posting, handled by JavaScript here (cb is chatboard number):
function CB_Post() {
jQuery.ajaxSetup({ contentType: "application/x-www-form-urlencoded;charset=utf-8" });
//alert($("#message").val());
//$("#fm").serialize()
$.post("do.aspx?do=add", { message: $("#message").val(), cb: $("#cb").val() }, function (data) {
if (data == '') {
document.getElementById("message").value = '';
FC('message', iMaxChar);
} else {
alert(data);
}
}, "text");
My implemetaiton so far is:
public void PostData(string text)
{
var data = new NameValueCollection();
data.Add("message", (#text+#"\n"));
data.Add("cb", "0");
client.Headers["contentType"] = "application/x-www-form-urlencoded;charset=utf-8";
var result = client.UploadValues("/cb/do.aspx?do=add", data);
}
This works and the message get sent, but it ends up as a empty string in the chatroom, even if i just send "hey".
Am i missing some kind of formating or encodeing/decoding here?
Well you would think there would be some security that would be preventing you from posting like that so that might be the issue.
However I suspect that do.aspx is expecting JSON data not a NameValueCollection object.
If you take a look at this post it seems the recommended route is to use a Dictionary<string, string>() and then serialize it with the JavaScriptSerializer().serialize.