I just wanted to clarify a few questions I have. I'm building a JSON string and returning it using context.response. I'm just calling a url to an .ashx handler and trying to return JSON.
Here's how I have approached it so far:
List products = GetCarolProducts();
List images = new List();
foreach(Product p in products)
{
string imageTag = string.Format(#"<img src=""{0}"" alt=""""></li>", Util.ImageUrl(p.Image, false));
images.Add(imageTag);
i++;
}
string jsonString = images.ToJSON();
context.Response.Write(jsonString);
I'm using the example helper method here for the JSON: http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
So my questions are:
1) I didn't want to pass back the entire product object. In fact I didn't want to pass that back at all. I wanted to pass back a bunch of image tags that I made in my foreach loop. so what I did was just create that string in each iteration of product and added it to a new generic list of type string. I assume this is fine, and that passing a generic string list can be serialized into JSON...that string is an object itself so this should be fine? thing is, it's not going to have any properties so I don't know. I guess I would be leary if this is going to work as if I were to pass an object such as product for example, it at least has properties in it such as ID, Name, etc.
So if this is not going to work, I am wondering how I can just receive back a list of JSON that gives me . I believe though I still need to be able to access that returned JSON with key/value though. But in terms of data, that's all I need in my jQuery, just a bunch of images.
So therefore my question is, must I pass an object that has properties in it so that my returned JSON has some params I can picked up via the jQuery since jQuery creates a nice typed object for you based on those properties? I don't think sending a generic string list would work in my situation then.
so not quite sure how to set this up and pass only the list of images to my ToJSON helper method and ultimately to my jQuery JSON parsing.
2) Not sure if I need to do anything special to tell the context.response that it's JSON other than pass it the final string that the helper method here creates? with XML you'd have to tell the response to format it as XML with context .Response .ContentType = "text/xml". So do I need to specify anything if I'm passing back JSON strings?
For the response content-type, look at Douglas Crockford's JSONRequest proposal.
Content-Type: application/jsonrequest
Related
I'd like to add some query string parameters to the GetFromJsonAsync helper method from the 'System.Net.Http.Json.HttpClientJsonExtensions' library. Reading through the docs and examples, it seems like this helper is more for vanilla API calls that do not provide a lot of intervening for custom headers or parameters, but I don't have clarity on this. It appears to add custom parameters or headers, the preferred method is to use the more raw, HttpClient.GetAsync Method.
I suppose I can just string manipulate the requestUri parameter of GetFromJsonAsync but I'm not seeing this as a mainstream practice. I just want to add some simple query string parameters like the following:
'zip': 90210
'units': 'imperial'
What is the correct or mainstream way to manipulate the Http call to an API for parameters or headers in a Blazor application?
I found this works
var data = await Http.GetFromJsonAsync<MenuApiModel>($"{nameof(Menu)}?menuId=1");
Notice I simply put the query param in the url itself.
I hope that helps.
I have made a gridx grid that uses a JsonRest Memory store from the dojo framework
http://dojotoolkit.org/reference-guide/1.10/dojo/store/JsonRest.html
the issue is I do not know how to pull out the sort parameter from the query string.
The url being formatted from the JsonRest call is
/admin/sales?sort(+DealershipName)
using the following statement gives me a null error
String sort = Request.QueryString["sort"].ToString();
Looking at the debugger I see the following (I need more rep to post images :( )
ok I can see that the following variables hold this value.
Request.QueryString = {sort(+DealershipName)}
type : System.Collections.Specialized.NameValueCollection
{System.Web.HttpValueCollection}
but the array is null.
I'm thinking I can do two thing. Parse the string myself or overload the dojo JsonRest Memory store. Parsing the string seems easier but if anyone has any idea or knows any libraries that can help me out. I would greatly appreciate it.
dojo/store/JsonRest has a sortParam property that you can set to the name of a standard query parameter to use instead of sort(...) (which it uses by default to avoid colliding with any standard query parameters).
For example, adding sortParam: 'sort' to the properties passed to the JsonRest constructor will result in the query string including sort=+DealershipName instead.
http://dojotoolkit.org/reference-guide/1.10/dojo/store/JsonRest.html#sorting
If the + also presents a problem, you can also override ascendingPrefix to be an empty string (''). Note that descending sort will still be indicated by a leading - (controllable via descendingPrefix).
I am not sure if this is a JSON.Net issue or a SolrNet issue, which is why I am tagging it with both.
I am using SolrNet and currently handling all page interactivity with JavaScript from an MVC call, by returning a JsonNetResult encoding of the object returned by solr.Query(). I am now experimenting with Faceting, but am not seeing the Facet info in my results.
I've got an MVC Controller method like the one below. (JsonNetResult is similar to the stock JsonResult, but encodes JSON using JSON.Net, described here.)
public JsonNetResult Index(string keywords)
{
JsonNetResult jsonNetResult = new JsonNetResult();
var documents = solr.Query(new SolrQuery(keywords), new QueryOptions
{
Rows = 10,
Facet = new FacetParameters
{
Queries = new[] {new SolrFacetFieldQuery("system")}
}
});
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.Data = documents;
return jsonNetResult;
}
I was expecting to see the faceting information encoded into JSON in the JsonNetResult, but all it contains is the array of hashes of the documents matching my query. Am I missing something in how SolrNet response objects work, or do I really need to parse through the object myself, and create something that JSON.Net can use to encode all of the information related to my query?
FYI, I have tried using a standard JsonResult in MVC, and the results are the same. Also, the reason I am using SolrNet and not just calling Solr directly and asking for JSON is because we do not want to expose the Solr search engine web interface directly to the user.
Since Solr can respond with JSON, if you want to return JSON directly to the view you'd be incurring some unnecessary overhead by having SolrNet deserialize a XML response, then serialize it to JSON. Instead, use SolrNet's components to skip the response parser. A couple of pointers to do this:
SolrQueryExecuter.GetAllParameters()
Low-level SolrNet
I am not sure if this is the best answer, but I have since been experimenting and found that if I change my original line from:
jsonNetResult.Data = documents;
to:
jsonNetResult.Data = new { Documents = documents, FacetFields = documents.FacetFields };
The data is at least serialized by JSON.Net. I guess I still don't understand the format of the object being returned by SolrNet's Query() method, since it seems like those properties (like FacetFields) should be serialized without me having to explicitly name them like I'm now doing above?
I am wondering how I can take a JsonResult in a unit test and get the stringified JSON to validate it. I have seen ways to use dynamic types to verify the data, but I need to actually verify the data gets converted to strings appropriately.
Here is my code where I create it:
JsonResult result = new JsonResult {Data = new {EncryptedValue = value}};
The value object I am passing in is actually an type I wrote that can take a value (int, double, DateTime) and when cast to a string, it encrypts the value and I need to ensure that the JsonResult is casting it to a string correctly when stringifying.
Just use result.Data
http://www.heartysoft.com/ASPNET-MVC-Unit-Testing-JsonResult-Returning-Anonymous-Types
You would need to mock the HttpContext and ControllerContext for that. See the link below.
http://blogs.msdn.com/b/miah/archive/2009/02/25/unit-testing-the-mvc-jsonresult.aspx
You can do this in a number of ways, it is very possible.
This blog post has a very nice implementation of custom tests written and explained.
In this post the author uses a custom type which is being returned and does the same thing.
I am using the ASP.NET command
var returnValue = new JsonResult { Data = items.Skip((pageNumber - 1) * pageSize).Take(pageSize) };
return returnValue;
to return the paged contents of a table via JSON, but when I got to try to parse it, in jQuery, the $.each takes each character as an individual element.
The output from that is along the lines of
[{"ItemNumber":1,"Description":"Description1"}, {"ItemNumber":2,"Description":"Description2"}]
listing all the rows and fields correctly. However this doesn't look like correctly formatted JSON to me (I beleive it should be encased in {}), is it?
If not what should I be doing to correctly output the table? If so, how can I loop round each element in jQuery, and extract the field values?
This is correctly formatted JSON.
You could try evaluating it with
var someVar = eval(jsonValue);
but this may lead to XSS.
Or even use this plugin.
This question may be related too.
Actually, using eval might be dangerous: unlike the case when it's enclosed in {}, it's possible to subvert the construction of an array. This occurs when eval tries to create an array using the Array constructor. See this post.
If you're not worried about that, you can use eval - for safety, the JQuery plugin in wtaniguchi's answer.
Can you not loop through like this?
for (i = 0; i <= returnValue.length - 1; i++){
//access your properties like this:
returnValue[i].ItemNumber;
returnValue[i].Description;
}
I don't know if using JsonResult will work like that, but if you return a list of objects in your server side code, it will work like that. Assuming you're using Asp.Net AJAX it will serialize automatically.
As far as I know there exists also the following json deserializer in Asp.net Ajax:
Sys.Serialization.JavaScriptSerializer.deserialize(...)
You'd have to browse for the exact usage since I don't know it by heard now.
I use the AJAX.NET function Sys.Serialization.JavaScriptSerializer.deserialize to get my JSON data when I've created it using System.Web.Script.Serialization.JavaScriptSerializer.Serialize.