jQuery and ASP.NET Article Part 2 Posted
I’ve posted part two in the (now) three part series of articles about jQuery with ASP.NET today. You can read the article here:
jQuery with ASP.NET (Part 2: Making Ajax Callbacks to the Server)
Part 2 of this article series deals entirely with various ways of interaction between jQuery and ASP.NET server side code for making AJAX callbacks. If you have any questions or comments regarding this article please leave them below.
If you missed Part 1 – it is an introduction to jQuery and focuses primarily on the client side features of jQuery.
An Introduction to jQuery (Part1: The Client Side)
Although this article uses ASP.NET for the sample discussed the content in Part 1 is really server platform agnostic.
Part 2: Focus on Ajax and Server Callbacks
The new article first introduces the basic features available in jQuery and then proceeds to demonstrate a number of different ways to call ASP.NET code. A wide variety of topics are covered from basic .load() calls to separate URLs, to same Page callbacks with Html and JSON data. The bulk of the article focuses on interacting with WCF and ASMX services for raw AJAX callbacks that treat ASP.NET primarily as a data backend for a client application. There’s also some discussion of using client side templating for rendering and maintaining HTML in one place and several extensive sample applications are provided to demonstrate the concepts.
The sample project also includes a host of utilities and what is basically the West Wind Ajax Toolkit Version 2.0. The jQueryControls project contains a number of server controls that simplify a number of client scenarios and also includes a few useful utilities like the ClientScriptProxy, ScriptVariables and ScriptContainer components. The tools have all been updated to work with jQuery on the client.
The article is fairly long (yeah, yeah what else is new?) , mainly due to a fair number of code listings and detailed discussion of some of the examples. As I was writing this thing I was trying to incorporate a number of the questions and comments I’ve heard in the last few months. Hopefully some of you will find this useful.
I thought I was going to do only two parts in this series, but since I ran a bit long on the AJAX portions I decided to leave the server side integration topic (server control creation, wrapping client functionality etc.) for another article. Not only would this article have gotten too long but it would also have blurred the focus at the end. Eeek, two down one more to go…
Other Posts you might also like
The Voices of Reason
# re: jQuery and ASP.NET Article Part 2 Posted
This is a great article. Well written and really opened my eyes about what is possible using jQuery.
Lee
# re: jQuery and ASP.NET Article Part 2 Posted
Why not use pagemethods if you want to post back to the same page.
This gives you a much cleaner way to specify your callback method.
Instead of figuring it out in the page load, you directly call the pagemethod...
Just a thought
Tim
# re: jQuery and ASP.NET Article Part 2 Posted
There's a place for doing manual routing if you need access to other content in the page or rely on controls that are defined on the page. For example, the list view rendering example wouldn't work from a Page method because the listview is defined on the page itself and you don't have access to that from Pagemethods.
That doesn't make it a bad choice - it's just closer to the service implementation which I would always recommend instead of page methods for purposes of separation of concerns.
# re: jQuery and ASP.NET Article Part 2 Posted
This is a fantastic post! It came at a time when I was working with jQuery and ASP.NET MVC and wanted a simple control to query a JSON service. Thanks very much! By the way, the stock server burps as it can't find the database! Will you post the database MDF or the SQL script create the database?
Cheers,
indy
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
cheers,
satish
# re: jQuery and ASP.NET Article Part 2 Posted
$.getJSON("Default.aspx?Callback=getRiskbyId", { RiskId: Riskid }, function(result) {
// Retrieve the Item template
var template = $("#grdRiskValues").html();
// Parse the template and merge stock data into it
var html = parseTemplate(template, result);
alert(html);
});
i am getting result not defined error from the parse template method.. can i know why is that and how to solve it
# re: jQuery and ASP.NET Article Part 2 Posted
@satish - you need to step through your code and see what is actually returned in result. The template should not reference result only its properties.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
thank you for an amazing article about using jQuery with ASP.Net. You really saved me a ton of time.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
The each loop only aims to find the first property by looping over it and then exiting. It's just to return d.firstProperty when callback is called. It's not looping over all properties - in fact there should only ever be one so technically the break isn't necessary, but this is obviously confusing and the break is another reminder.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
One thing...in the _readme.htm, it says WcfAjax is a WAP project but I don't see it. I only see WcfAjaxBusiness. Is that a typo? I am able to run with cassini, but when I try using virtual directory I get "Callback Error: undefined"
I am new with WCF, so I may be missing something here...
# re: jQuery and ASP.NET Article Part 2 Posted
As to virtual - make sure the virtual is properly configured. You should load the .svc file in the browser to see if it works and follow instructions if it doesn't. Make sure you only have 1 kind of authentication (ie. Anonymous OR Windows but not both) as WCF only supports a single auth mechanism.
# re: jQuery and ASP.NET Article Part 2 Posted
Thanks for the great examples.
What if I need to pass a complex JSON stock object to my WCF service similar to Listing 5?
JSON Example: {"stocks":[{"symbol":"msft","investorinfo":{"sharesowned":"500","datepurchased":"12/01/2008","price":{"purchasedprice":"20.00","commision":"19.95"}}},{"symbol":"goog","investorinfo":{"sharesowned":"100","datepurchased":"12/01/2008","price":{"purchasedprice":"300.00","commision":"19.95"}}},{"symbol":"aapl","investorinfo":{"sharesowned":"50","datepurchased":"12/01/2008","price":{"purchasedprice":"100.00","commision":"19.95"}}},{"symbol":"intc","investorinfo":{"sharesowned":"1000","datepurchased":"12/01/2008","price":{"purchasedprice":"15.00","commision":"19.95"}}}]}
How would I then configure my WCF method? Is there anything special to do to the $.ajax call?
# re: jQuery and ASP.NET Article Part 2 Posted
Ideally the way you want to do this is use the server to give you an existing object - either do a load or new operation. That way you have the server serialize you a C# object marshalled to the client. You can then re-populate that object and send that back to the server which will guarantee that the object can be passed back.
WCF's deserialization will deal with missing properties.
Note though you do need a full type description - you can't take object as a parameter and accept a generic input value - it has to be a specific type.
# re: jQuery and ASP.NET Article Part 2 Posted
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json)]
public void stocks(List<Stock> stocks)
{
// Do Something
}
However stock is null.
Any suggestions or good examples?
# re: jQuery and ASP.NET Article Part 2 Posted
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json)]
public void stocks(List<Stock> stocks)
{
// Do Something
}
However stock is null.
Any suggestions or good examples?
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
{"stocks":[{"symbol":"msft","investorinfo":{"sharesowned":"500","datepurchased":"12/01/2008","price":{"purchasedprice":"20.00","commision":"19.95"}}},{"symbol":"goog","investorinfo":{"sharesowned":"100","datepurchased":"12/01/2008","price":{"purchasedprice":"300.00","commision":"19.95"}}},{"symbol":"aapl","investorinfo":{"sharesowned":"50","datepurchased":"12/01/2008","price":{"purchasedprice":"100.00","commision":"19.95"}}},{"symbol":"intc","investorinfo":{"sharesowned":"1000","datepurchased":"12/01/2008","price":{"purchasedprice":"15.00","commision":"19.95"}}}]}
# re: jQuery and ASP.NET Article Part 2 Posted
As I said - the easiest is to look at the serialized object and mimic that structure to pass back to the server.
FWIW, I think it's really bad practice to send back this much data to the server. If you're building apps like this it's often recommended to updates in small chunks - ie. update each stock/portfolio instance individually rather than taking the 'DataSet' approach of modifying a whole set and sending the whole thing back.
# re: jQuery and ASP.NET Article Part 2 Posted
You are talking about load function and saying that its format is
$(sel).load(url,callback)
jQuery documentation at http://docs.jquery.com/Ajax/load#urldatacallback says that a format is
load( url, [data], [callback] )
where "data" stands for "Key/value pairs that will be sent to the server".
If I'm not mistaken, your following LDK Stock example
function showStockQuote() {
$("#divResult").load("StockDisplay.aspx", { symbol: $("#txtSymbol" ).val() });
}
follows "load( url, data)" format. "data" is supplied, while "callback" is not. This mistake makes it hard to understand your explanation.
I would tell that a load format is
$(sel).load(url,[data],[callback])
and that in your LDK Stock example "{ symbol: $("#txtSymbol" ).val() }" is "data" parameter.
Thanks.
# re: jQuery and ASP.NET Article Part 2 Posted
"FWIW, I think it's really bad practice to send back this much data to the server. If you're building apps like this it's often recommended to updates in small chunks - ie. update each stock/portfolio instance individually rather than taking the 'DataSet' approach of modifying a whole set and sending the whole thing back."
Are you referring to tw's post (12/15 at 12:36pm)? So, when passing back an array of data like the stock symbols, would you recommend doing a javascript loop on the client side and sending each symbol's data to the server per loop?
for (var i = 0; i < myStocks.length; i++)
{
(ajax call sending each stock symbol's data to server here)
};
thanks
# re: jQuery and ASP.NET Article Part 2 Posted
The point is to not hold stale information on the client, but update the server in small/atomic and hopefully logical chunks.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
Cheers,
Chris
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
thanks
# re: jQuery and ASP.NET Article Part 2 Posted
I must say I was quite disappointed to get the code and find I need Sql 2008 to use it. I will still learn from it but not near as easily. It would be nice in the future to try and keep sample code usable by the majority and not littered with other new technologies.
# re: SQL Server 2005 Support
# re: jQuery and ASP.NET Article Part 2 Posted
thanks for the great article and accompanying sample projects. i am learning a lot from this.
i think you have mentioned in one of your blog that JSON.net has option to configure settings one being handling recursion loop. wouldn't it be great to have it in your WestwindJsonSerializer as well?
i was playing with it and ran into StackOverflow exception. it was coz i have two objects that has reference to each other.
appreciate your contribution to the community and keep up the good work!
cheers
# re: jQuery and ASP.NET Article Part 2 Posted
I haven't updated this yet, but it should show up in the repository for the jQueryControls in a bit.
# Sql Packager File
Wow, your on top of things. It seems the demo code ZIP hasn't changed, is there somewhere else to look for the wcfAjax.exe file that I am not aware of.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
It is not in the "http://www.west-wind.com/files/conferences/jQuery.zip" file or I am somehow doing something stupid?
# re: jQuery and ASP.NET Article Part 2 Posted
Thanks for such wonderful articles.
I'm stuck up with a problem. I need to fill an empty DropDown List with the values from Database( thereby calling ASP.NET Page methods through jQuery) when user clicks on it. Currently $("#DropDown").click() is being successfully called, but when I'm using $.ajax method inside this function to call ASP.NET Page methods it doesn't work. Please provide your useful inputs for this.
Thanks & Regards,
Amin Sayed.
# re: jQuery and ASP.NET Article Part 2 Posted
/*! * ww.jQuery.js * West Wind jQuery plug-ins and utilities * * Copyright (c) 2008 Rick Strahl, West Wind Technologies * www.west-wind.com * * Licensed under MIT License * http://en.wikipedia.org/wiki/MIT_License * * Version 0.90.672 - 12/01/08 */
# re: jQuery and ASP.NET Article Part 2 Posted
I have validation.js and AJAX UpdatePanel to download a file on the server. As soon as I upload the file the page is broken- doc.ready () is not firing again I think and my validation rules error. How do I fix this?
# re: jQuery and ASP.NET Article Part 2 Posted
You are one of my favorite bloggers.
Thank you for your hard work.
Amazing.
# re: jQuery and ASP.NET Article Part 2 Posted
Thanks
Dan
# re: jQuery and ASP.NET Article Part 2 Posted
You have some great articles which I enjoy reading about. I wonder if youcn help me.
I have 3 HTML checkboxes which are programmed via jQuery click() event so that when a checkbox is clicked it's value is returned through the .ajax() call into my aspx page.
The aspx page uses this value in one of my database methods to get a datatable of results for this value. I then assign this to my GridView control through .DataSource and bind the data using .DataBind().
But nothing happens. I have debugged the code and the call to the database was successful and I can see the data in the DataTable.
When I use this DataTable to create an HTML table it works. But is there anyway that I can get to populate the GridView control?
# re: jQuery and ASP.NET Article Part 2 Posted
I'm hopeful of seeing a demo, perhaps using Northwind, of something like the ability to page through products, one or more products at a time, where users with javascript enabled get the ajax response via json (with history), and those without javascript automatically get a normal url page refresh.
I've been looking for such a demo for MVC but not found anything. I did find a jquery plugin call Ajaxify that does such paging but would prefer to see some code from MS.
# re: jQuery and ASP.NET Article Part 2 Posted
I want to call a jquery function from my .cs page. I have made a plugin called jquery.xyz.js.
I have registered it on my aspx page. i have made a function in this plugin as follows :
$.extend($.fn, {
SelectMenuProcess: function(MainElemID) {
return this.each(function() {
document.getElementById("check").className = "section-" + MainElemID;
});
}
});
Iam calling this function from the .cs page as follows:
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "startup", "<script type=\"text/javascript\">SelectMenuProcess('" + Request["Tab"] + "');</script>");
When i execute this code, firebug shows error ie "SelectMenuProcess" is undefined.
I going wrong in plugin formation. Can you please help. i have gone through several articles like: http://docs.jquery.com/Plugins/Authoring etc
regards
prabhjot
# re: jQuery and ASP.NET Article Part 2 Posted
This article is very good!!!
cheerio.
# re: jQuery and ASP.NET Article Part 2 Posted
Thanks buddy, these are great articles with regards to JQuery and ASP.NET.
A mate of mine had said to me that after using JQuery and ASP.NET together, it changed his entire view on ASP.NET and i think these articles will enable me understand better how the 2 come together. Thank you
Best
Muzi
# re: jQuery and ASP.NET Article Part 2 Posted
is it possible to return empty list rather than null value coz null value returned causes onerror method to be triggred on client side.
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
Hopefully this is useful to some :)
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
I spent whole day to search jquery with asp.net sample and article, yours is the top one.
From here, I'll start to learn jquery.
I downloaded zip file from www.west-wind.com/files/conferences/jQuery.zip.
There are no PhotoAlbum and WcfAjax two projects.
Where to download PhotoAlbum and WcfAjax two projects?
# re: jQuery and ASP.NET Article Part 2 Posted
:)
I have always found your blogs helpful.
I was looking for JQuery Templating stuff and again found yours to be the best.
Keep up the good work.
Good stuff!!
# re: jQuery and ASP.NET Article Part 2 Posted
<script language="javascript" type="text/javascript">
$(this).ready(function() {
$("#GetPdf").click(function() {
theHtml = $("html").html()
$.download('<%= Url.Action("AgreementDetailsPdfReport","Reports") %>', { filename: "AgreementDetails", format: "pdf", html_: theHtml }, "post");
});
});
</script>
# re: jQuery and ASP.NET Article Part 2 Posted
# re: jQuery and ASP.NET Article Part 2 Posted
Here's my code,
Server Side:
public void GetClient(Guid clientId)
{
InformationEntities context = new InformationEntities();
var query = from c in context.Clients
where c.ClientID == clientId
select new {
c.FirstName,
c.MiddleName,
c.LastName,
c.Locality,
c.LandPhone,
c.CellPhone,
c.DOB,
c.Email,
c.IsActive,
c.PAN,
c.TAN,
c.Remarks,
c.BankAccount
};
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
String res = ser.Serialize(query);
context.Dispose();
Response.ContentType = "application/json";
Response.Write(res);
Response.End();
}
Client Side:
function PopulateFormFields(){
$.getJSON("EditClient.aspx",{clientId:qs}, function(data){
$("#FirstName").text(data.FirstName);
});
}
The page on response just tries to save the returned JSON object :'(
Can't figure out what is wrong, can you have a look?
Regards,
Joy
# re: jQuery and ASP.NET Article Part 2 Posted
Great Articles. Will be great if u can the link to3rd article
# re: jQuery and ASP.NET Article Part 2 Posted
The first time I used jQuery to call a service and plop stuff into a DIV tag was rather exhilarating, but I'm not quite sure why...