Accessing ASP.NET Server variables in jQuery - asp.net

In Page_Load() function, I have populated an arraylist and a hashtable. I need to read their values in the $(document).ready(function(){...}.
I am a beginner in terms of ASP.NET and jQuery. Please suggest a way to do it.
cheers

you can use PageMethods to make a call to your aspx page from JS. Here is a nice article on how to use page method with jQuery. You can return your "whatever" in your page method. If you want to serialize your server side objects before passing them to the client side, you can serialize them to JSON . Here is an example. You would just read your json data after your ajax call is successful("success: function(msg){//do something}") and update your HTML accordingly

you can use Page.ClientScript property to register arrays, scripts etc.
For more information view MSDN

you can create a page.method in server side and call it in the client side script that return an array of values
by adding
<scriptManager EnablePageMethods="true">
in the server side you create a function that return an array of values
ex: GetArrayResult()
if you intersting in this i will give you the rest of example

JSON.Net will help you serialize the hashtable and array to JSON, and you can store these in a hidden field. Then on the client side you can deserialize the strings to your javascript variables with:
var array = JSON.parse($('#hiddenTextField').val());

Related

Passing session object to angularjs function in razor view MVC

I need to pass the asp.net session object to a function that I call in ng-init.
something like this;
ng-init=initUser( #((User)Session["userSession"]) )
I just want to pass my "User" object to the initUser method declared in angularjs. Is there a way to do it ?.
I have searched for a solution and all are suggested to call an action method in the controller inside the "initUser" method and fetch the session object from the server and assign it to angularjs scope variable.
Thanks.
The solution you searched and got as the response is more elegant since the front-end would query the data from the server and serve it through an API.
However if you want to inject the .NET session to javascript you could Json encode it to a variable and add it to the scope.
var json = #Html.Raw(Json.Encode(#((User)Session["userSession"]));

return json from pageload in asp.net + populate other data

I have an aspx page - and on the page load I need to populate field with information (the regular way - txt1.Text ="abc" etc).
But, I also need to return a json object in order to use it on the $(document).ready(...)
Can I return those 2 type of information on the page_load? and how?
I can't use ajax after page load - I need all the information to be load with the page_load
Thanks.
You can make an ajax call on the dom ready to the server to get your json data. http://api.jquery.com/jquery.ajax/ you would need a service to hit from your ajax request to pull your json data back to render it on the page. There are a few options in asp.net including .ashx handlers, web methods https://msdn.microsoft.com/en-us/library/byxd99hx%28v=vs.90%29.aspx, and others.
Store your JSON string in a HiddenField, then read and parse it in the ready handler.
C#:
JsonField.Value = myJsonString;
JavaScript:
$(function(){
var json = $("#<%=JsonField.ClientID%>").val();
var obj = JSON.parse(json);
});

Is there a way in ASP.net to fetch data from database using Jquery(not using Webservices/WebMethods)

Is there a way in ASP.net to fetch data from database using Jquery Ajax Method. I know that i can easily access the data by creating a webservice and get it from there using Ajax.
What I want to know is that how can I get the data from simple class methods which accesses the database rather than creating a webservice.
One way can be is to write a HTTPHandler and call that handler using Jquery to retrieve the data.
Check this out for a super-easy (lazy) way of doing a return straight from a public method defined in your aspx.cs file:
asp.net web forms json return result
Example shows putting [WebMethod] and [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attributes on top of the method allows you to call directly from ajax client side request. Worth considering securing this method though to prevent calls from elsewhere!

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.

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/

Resources