json Data Output in ASP.NET - asp.net

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.

Related

Is it possible to return a html table from a WebMethod?

Using a WebMethod, I get a value needed to create a HTML Table and populate it.
Once it's done, I need the Table to be displayed.
Is it possible ?
Can a web service return an HTML table? Yes. Should you do it that way? Probably not. Please consider 'separating the concerns' so that the service is responsible only for returning the data. Then the consumer of the data can format it as needed. One possible implementation would be for the service to return XML and the 'presenter' to transform it with XSLT into the desired Table. In the long run, the code will be easier to maintain and understand. (Trust me; I've seen a project that had 2,500+ lines of string concatenation that built an HTML string. NOT fun!) As an added bonus, the web service's response will be much smaller.
You can return a string from a WebMethod, which means you could return a string that represents html... then render that string (taking care of required encoding) I cant say much more that that not knowing any more...
Create the markup in a variable and do Response.Write.
StringBuilder strHtml=new StringBuilder();
strHtml.Append("<table>");
strHtml.Append("<tr><th>Name</th></tr>");
strHtml.Append("<tr><td>Jon</td></tr>");
strHtml.Append("<tr><td>Marc</td></tr>");
strHtml.Append("<tr><td>Jared</td></tr>");
strHtml.Append("</table>");
Response.Write(strHtml.ToString());

Why have a separate call to get Json?

I need to get some Json to the client side from the server and it's somewhat troublesome as almost all tutorials assume an Ajax call to a separate action to get the Json.
This led me to think that there must be some reason why it is done this way. In Asp.Net MVC we can pass a Model along with the view to get the information but we can't seem to easily pass a Json object. Instead you are supposed to make a separate call to get this information.
What if the Json info is known when the page is generated, why not generate it at the same time?
I'm sorry if I wasn't clear enough. While it's nice to hear of ways to get Json to the client, the question is actually whether there is a specific reason the Ajax call method is much more popular, like security or anything like that.
Can you put something like this into your view? (rough pseudo code, assuming using a Razor view)
< script >
var myJSON = { Field: #model.Field, Field2: #model.Field2 };
< /script >
Because you do not need both at the same time... on the first call will be to get html (the view of the data - represented by a view model), and any ajax calls will be to get the possibly updated data (json serialized view model).
No reason why you can't. You could use the javacript serializer to create a JSON string that drop on the page. You could also create an action that return the json string that you called from a script tag.
What you want if you're using KnockOut, would be the Mapping plugin that turns an ordinary JS object, like that generated above, into an observable ready for KnockOut to use. See here from info. http://knockoutjs.com/documentation/plugins-mapping.html
You can use content-negotiation by setting accept header. This is considered a best practice (and according to some RESTful).
This needs to be supported and implemented at server as well. ASP NET MVC does not make it easy to support content-negotiation and you have to implement it yourself by if-else or using ActionFilter and implementing action selector.

ASP.NET: Is it possible to create dynamically-named Javascript functions without using .NET code (ie, VB.NET or C#)?

I have a custom user control (ascx) that contains a textbox and a Javascript-based counter to let the user know many characters they have left to type. In this control is the following:
function GetTextBox() {
return document.getElementById("<%=txNotes.ClientID %>");
}
This worked fine when we only had one instance of this user control on the page, but now we have to support multiple. As you know, having multiple instances of this control on a page will result in multiple GetTextBox() functions, only the last of which will be called no matter what. To support multiple instances, I use this:
if (!string.IsNullOrEmpty(TextBoxName) && !Page.ClientScript.IsClientScriptBlockRegistered(TextBoxName))
{
string Script = string.Format("function Get{0}Notes() {{ return document.getElementById(\"{1}\"); }}",
TextBoxName, txNotes.ClientID);
Page.ClientScript.RegisterClientScriptBlock(GetType(), TextBoxName, Script, true);
}
TextBoxName is a public usercontrol property, so if the developer passes Employee through, it will generate a Javascript function called GetEmployeeNotes(). This works greate because now we can have a unique GetNotes() function.
However, I don't like how it's hardcoded into the codebehind. I would like a markup-based solution for this, something that doesn't require a rebuild of the project in case I want to change the Javascript. Does anyone know of a way to do this?
Edit: I've already thought of creating a separate .js file that I could read with a text reader, but that sounds a bit hacky and I'd like to avoid that if at all possible.
Edit 2: Guard's answer below would work, but I don't want to go that route for the reason I gave beneath his answer. If no one can offer another way to do what I want to do, I will most likely mark his as the answer since it technically does exactly what I am asking.
I'm not a .NET specialist, but isn't it working as a preprocessor?
Isn't it legal to write
function Get<%=Name %>Notes() {...}
?
Why not use a generic function and just pass the id of the corresponding textbox? As in: GetNotes(thisTextBoxId) {...}. Not only would that deal with your problem but also is more DRY.

How to pass array from Asp.net server side to Javascript function on client side

How do I pass an array I have created on the server side onto the client side for manipulation by Javascript?
Any pseudo code will help
You'll need to embed it as a javascript array declaration into the page. There are a number of ways to do this, but it generally means turning the array into text that you write to the page, probably using the ClientScriptManager.
I'm hoping for better javascript integration in a upcoming verison of ASP.Net. Moving the value of a server variable —any server variable— to the client ought to be supported with a simple, one-line function call. Not the back-flips we need right now.
Convert it to string representation of a javascript array ("['val1','val2','val3']") and shove it into the value field of a hidden input.
Another way would be to use the RegisterArrayDeclaration method of the Page object (deprecated) or in the ClientScriptManager class. See MSDN for details.
The way I do it is like this:
aspx:
private string buttonarray = "'but1','but2','but3','but4'";
public string Buttonarray
{
get { return buttonarray; }
}
javascript
var buttonarray = new Array(<%=Buttonarray%>);
I hope this helps.
Easiest way is to convert it to json. Then just put it at the top of the page in a variable. I've found this the best json implementation for .net: http://litjson.sourceforge.net/

JSON string to list or other usable format in asp.net 2.0

I have one JSON that is coming in a string format. I need to store it in a key-pair value or something like that. I am using asp.net 2.0 and can not use 3rd party DLL like Newtonsoft.Json.dll. I guess last option will be to use regular expression.
Can anybody please help me in this?
If you go to http://www.json.org/ and look towards the bottom of the page there are dozens of json libraries most of them open source, I believe they list 8 for C#. If you can not reference one of these libraries, I think your best bet would be to find one with a permissive license and simply add the code to your project.
Another idea is to look at the diagrams, grammer, and syntax at http://www.json.org/ and just write your own parser, but regex is NOT the way to do it. If you dont know how to write a parser you could look at one of the open source json libraries or start with something less complicated like a good CSV parser, here is a paper that looks pretty good: http://www.boyet.com/Articles/CsvParser.html
It is possible to serialize JSON using JScript in C# into key/value pairs. You need to add a few references to your project. They're part of the .NET framework, you just need to add the references to your project. You'll need:
Microsoft.JSript
Microsoft.Vsa
First, the usings at the top of your class:
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
Then the Engine that will execute the script needs to be initialized somewhere in your 'Page' code-behind:
VsaEngine Engine = VsaEngine.CreateEngine();
Then you just create this method and call it by passing in your JSON object:
object EvalJScript(string JScript)
{
object result = null;
try
{
result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
The type of object returned (if JSON is passed in) is a 'JSObject'. You can access its values as key/value pairs. Read the MSDN documentation for more details on this object.
Here's an example of using the code:
string json = "({Name:\"Dan\",Occupation:\"Developer\"})";
JSObject o = EvalJScript(json) as JSObject;
string name = o["Name"] as string; // Value of 'name' will be 'Dan'
Could you use JScript.NET?
If so, should be easy enough with eval() - then just loop through the objects returned and translate into KeyValuePair's or whatever
You will need to use jscript.net as the code behind language, but other pages of your site should be fine to stay as c# if thats what you prefer.
As mentioned in previous comment, you will need to be aware of the security aspects and risks - only use eval if you trust the JSON you're parsing!

Resources