I have an ASP.Net application that has a UserControl that needs to be rendered on an ASPX page (as normal), but also via Ajax using a Handler.
One solution to this is to get the UserControl to simply build up a HTML string, rather than rendering controls as it would normally.
That way, the ASPX page can simply populate a Literal control with the output, while the Handler can write the output to the Response object for Ajax to pick up.
Is this the ideal solution? are there any drawbacks of this approach?
If you do that, you have to recreate the user control every time from the client-side when a postback to the server happens. However, performance wise, that may be better. However, I don't think the UC can then participate with viewstate and the ASP.NET object model as a typical user control would. You would have to account that all actions within the UC are handled appropriately, to react to the web.
If you have a large amount of content to render, the UC approach is just fine. We're talking rendering markup and injecting it into the UI, and so that does pan out and can make it easier. If it's not that much markup, any alternative would do.
If all you need to do is push data to the client, an alternative could be that you push JSON to the client through a web service, and build the UI on the client. That's efficient too.
HTH.
There are a number of JS templating tools available now that will solve this problem. Take a look at mustache js, which can allow the same template to be rendered in client side JS and in C#.Net.
You can then create on template file and either render the HTML in JS via Ajax or render in .Net and simply output during page load.
Related
I have a specific page (sitecore content item) in my web application composed of a sitecore layout and many sublayouts. One of those sublayouts is a user control that I would like to have refreshed once a certain button is clicked. I would like only that sublayout to be refreshed and the rest of the page to remain unchanged (typical ajax situation here). How do I accomplish this with sitecore when all of my sitecore content items are directly related to a full page in my web application (layout with sublayouts)? In my case, I want to use ajax to return the content of a specific, single sublayout only. What is the best practice for this kind of ajax situation with sitecore? I'm using sitecore 6.5.
Since you use the phrase "partial page update", I assume you are using an UpdatePanel. This doesn't really function any different than it would in a traditional ASP.NET application. You will handle the button click in a server-side handler method, modify properties on controls and let the update panel handle the rest.
If you are not using update panel, you have a few options depending on exactly what you want to achieve.
Typically, if you are clicking a button to trigger an ajax request, you are posting some data back to the server. For this case you would usually set up a web service to process the data and return some result. Your service can access Sitecore data, but does not utilize the Sitecore presentation engine.
Another option would be to make the request to a Sitecore page (possibly the same as the original request), but include a querystring parameter to trigger a different device. You could configure this device to render JSON, XML or a fragment of HTML rather than the normal Layout and battery of sublayouts.
Another option would be to use the Sitecore Item Web API. If you go this route, you will have another array of options (and a bit of a learning curve as well). Start by reading the documentation on SDN or some of the many blog posts on the topic.
There are a number of options available for achieving asynchronous behavior. None of these really relate to Sitecore directly, however, there are some Sitecore specific things to watch out for which I have highlighted below.
UpdatePanel Control
If you are performing something trivial where ultra-fast performance isn't a concern, simply wrap your button (and any other .NET controls that you would
like updated) in an UpdatePanel Control. You will also need to drop
a ScriptManager control into your base layout near the top inside
the <form> element. NOTE: When using this method, you will need to ensure that that your Sublayout does NOT have caching enabled, otherwise your button will not postback properly
Create your own web service
In this scenario, there are many client-side frameworks available for achieving the same result. My preferred method is to hook onto the client-side button click event with jQuery, prepare a request object, and post it to the server (getting back the information you need to update the client).
Here are a number of web service options that work with Sitecore - allowing you to have access to the Sitecore.Context and all of the subsequent Sitecore APIs.
Create an empty ASPX Web Form that accepts parameters as query strings. In the Page_Load method, do some work with the parameters and write directly to the response using Response.Write(). A JavaScriptSerializer comes in handy for serializing to JSON, just be sure to set Response.ContentType = "text/javascript";
Create an ASMX Web Service and decorate your methods with [WebMethod] (or [WebMethod(EnableSession = true)] if you need access to Session data).
Use MVC Controllers (ex: ASP.NET Web Api) to create an API. I believe there are some issues to work around in Sitecore 6.5 as described here.
Since this is all contained within a single Sublayout, you could simply use a standard <asp:UpdatePanel> surrounding your button and the usercontrol. In the code-behind, you can then do whatever databinding / data retrieval necessary to update the content of the usercontrol.
Note, if the button was on a different sublayout to the one where the content needs to be updated, you can use the approach described in this question as long as both controls have their content within <asp:UpdatePanel>.
In answer to your other question:
What is the best practice for this kind of ajax situation with sitecore?
There's not really a Sitecore-specific best practice for this sort of thing. In this case, any approach which works for plain ASP.NET will also work with Sitecore. The approach I described above is probably the simplest and quickest to implement, but you could also do this via jQuery and ajax to call a web service to load updated content.
suppose i have many heavy control is on the page. as for example i have three gridview populated on the page and one gridview & button is inside the updatepanel. from this scenario we can understand that there will be huge viewstate on the page. so i want to know that if i click on button inside the updatepanel then all the viewstate will be submitted to server during partial postback or not. if huge viewstate submit to server and comes back to client then what is the advantage of partial postback because response time will be slower. so tell me how could i tune up the code that only required things will only submit to server. discuss the partial postback concept in detail as a result we can take right action to have good performance. thanks.
+1 to geek!
If you are concerned about the performance of your page(s), I would also recommend using ListView instead of GridView:
https://web.archive.org/web/20211020153238/https://www.4guysfromrolla.com/articles/122607-1.aspx
http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui.aspx
http://basgun.wordpress.com/2007/12/27/listview-control-in-aspnet-35-1/
http://basgun.wordpress.com/2007/12/28/listview-control-in-aspnet-35-2/
http://basgun.wordpress.com/2007/12/29/listview-control-in-aspnet-35-3/
http://basgun.wordpress.com/2007/12/30/listview-control-in-aspnet-35-4/
You can also visit Matt Berseth's blog to see how ListView can get very handy (and neat) for different types of development scenarios:
http://mattberseth.com/blog/listview/
it's important to keep in mind that an UpdatePanel's partial postback invokes a full page life-cycle on every single async request.
Please check out following links for pros and cons of the update panel.
Why ASP.NET AJAX UpdatePanels are dangerous
Why you should not place your whole site in an UpdatePanel
Are you making these 3 common ASP.NET AJAX mistakes?
so i want to know that if i click on button inside the updatepanel then all the viewstate will be submitted to server during partial postback or not
Yes, it will. The entire page's view state is transmitted (in its entirety) to the server on partial page postback, and the new view state is sent back (in its entirety) from the server back to the client on response.
I'd suggest you use a tool like Fiddler to examine the HTTP traffic between the browser and your server when making a partial page postback. This article provides an overview of using Fiddler - Troubleshooting Website Problems by Examining the HTTP Traffic.
In short, the UpdatePanel is meant as a quick and dirty way to get partial page postbacks without having to worry about client-side script or writing logic on the server to specifically handle a partial page postback. Such simplicity comes at a cost, as you've discovered. :-)
For more control over the content that is sent to and from the server on a partial page postback you need to write client-side script and create server-side methods or services to handle the Ajax requests. These articles offer various techniques for providing such functionality:
Accessing JSON Data From an ASP.NET Page Using jQuery
Using Ajax Web Services, Script References, and jQuery
Using WCF Services with jQuery and the ASP.NET Ajax Library
I'm dipping my toes into web development. Based on various bits of advice, I'm going to start by getting a handle on html, css and javascript.
I'm interested in Ajax, I've had a look at the client side code and that looks straight forward enough, I'm slightly confused about what I do on the server side.
I'm using IIS and ASP.NET. I've had a google but I can't find anything that is either simple or current. There's a lot of talk about the Ajax toolkit, which I believe are controls which use Ajax (and may be retired??) Everything else seems to be based on old versions which I don't trust.
So, in really simple terms, what do I have to do in IIS to respond to an AJAX call?
Quick aside, I believe we can use JSON for object serialisation?? I assume I don't need to in the interests of getting a simple sample running?
So I have an Ajax call which will have one parameter, and I want to return "something" based on the parameter. What is the simplest code to achieve that with IIS and ASP.NET?
Thanks
An AJAX call is basically just a regular call to your website. The only difference is how the browser handles it - AJAX calls are done in the background with Javascript (the J in AJAX) and then does something with the data. You could take the URL that you're doing an AJAX call with and put it in your address bar and it'll return the exact same data. So, basically, what you do on the server side is exactly what you would do as if it were a form being submitted, for example.
As far as object serialization, yes, JSON can do that.
First of all, doing ajax has nothing to do with IIS; it has to do with ASP.NET.
There are essentially 2 ways to do AJAX in .net
1) Heavy use of the framework. You can put your asp controls (such as literals, gridviews, listbox...) in a control called an updatepanel. For this to work, you need to add a script manager to the aspx page. Then, when the user raises an event (for example, paging and sorting of a table), the request is handled by the framework and only the part of the page that's in the updatepanel is refreshed. The other way to raise events is by using the __doPostback function that comes with the asp.net framework. The downside of this method is that a lot of data needs to go back and forth between the user and the server so it can be slow. The upside is that you don't have to worry about generating the HTML since the asp controls handle it for you.
2) Heavy use of Json. With this method, you can use jQuery to call a page method or a web service. You send a json object to the server and you get a json object back. With jQuery, this is really easy. The downside of this method is that you're getting just the json data back: no formatted HTML. So, if you're looking to have a table updated, this method would be tedious because you'd have to recreate the entire HTML. However, the upside of the method is that it's very fast because only the raw data is transmitted. If you implement a web service, you don't even need to create an entire page.
What do you need to get from the server?
If you want to return "something" from the server that's "simple" (just data), I'd recommend a web service with jquery to trigger the call. If the return data is "complex" (html code for controls) then I'd recommend using MS ajax with the update panel.
Don't use the AJAX Control Toolkit, ASP.NET AJAX library, updatepanels or the scriptmanager control. Microsoft have pretty much ditched the lot in favour of jQuery and its Plugins (sensibly).
Here are just some of the ways you can use AJAX with jQuery in ASP.NET: Many ways to communicate with your database using jQuery AJAX and ASP.NET
I'm retro-fitting a .aspx page with AJAX functionality (using VB, not C#). The codebehind populates the page with data pulled from a web-service. The page has two panels that are populted (with different data, of course) in this way. On a full page refresh, one or both panels might need to be populated. But populating Panel 2 can take a long time, and I need to be able to update panel 1 without refreshing Panel 2. Hence the need for AJAX (right?)
The solution I've come up with still has the old .aspx page with .aspx.vb codebehind, but introduces a Generic Handler (.ashx) page into the mix. Those first two components do the work on the user's first visit or on a full page refresh, but when AJAX is invoked, the request is handled by the .ashx page.
First question: Is this sound architecture? I haven't found a situation online quite like mine. Originally, I wanted to make the .aspx page into the AJAX handler by having the codebehind implement IHttpRequest, and then providing "ProcessRequest" and "IsReusable" methods, but I found I couldn't separate a regular visit to the page from an AJAX request, so my AJAX handlers took over even on the first visit to the page. Second question: Am I right to think that this approach (making the .aspx page do double-duty as the AJAX handler) will never work? Is it impossible to tell whether we're getting a full-page request or a partial-page (AJAX) request?
If the architecture is good, then I need to dynamically generate a lot of HTML in the .ashx file, right? If that is right, should I send HTML back to the client, or should I encode it in some way? I've heard of JSON encryption, but haven't figured out how to use it yet. So, Third question: Is "context.Response.Write" the only pipeline for sending data back to the client? And, if so, should I send back HTML or some kind of JSON-encoded objects?
Thanks in advance.
It sounds as if the page requires some AJAX functionality added to the UI.
Suggest using an UpdatePanel for each web form element that needs to have AJAXy refresh
functionality. That'll save you from having to refactor a bunch of code, and introduce a whole lot of HTML creation on your .ashx.
It'll be more maintainable over the long run, and require a shorter development cycle.
As pointed out by others, UpdatePanel would be a easier way - but you need to use multiple update panels with UpdateMode property set as conditional. Then you can trigger the update-panel refresh using any button on the page (see AsyncPostBackTrigger) or even using java-script (see this & this). On the server side, you may decide what has triggered the partial post-back and act accordingly by bypassing certain code if not needed.
You can also go with your approach - trick here is to capture the page output using HttpServerUtility.Execute in your ashx and write it back into the response (see this article where this trick has been used to capture user control output). Only limitation with this approach is that you can only simulate GET requests to your page and so you may have to change your page to accept parameters via query string. Personally, I will suggest that you create a user control that accept parameters via method/properties and will generate necessary output and then use the control on your page and in ashx (by dynmaically loading it in a temperory page - see this article).
EDIT: I am using jquery to illustrate how to do it from grid-row-view.
$(document).ready(function() {
$("tr.ajax-grid-row").click(function() {
$("#hidden-field-id").val($(this).find(".row-id").val()); // fill hidden filed
$("#hidden-button-id").click(); // simulate button click
});
});
You can place above script in the head element in markup - it is assuming that you have decorated each grid-row-view with css class "ajax-grid-row" and each row will have hidden field decorated with css class "row-id" to store row identifier or the value that you want to pass to server for that row. You can also use cell (but then you need to use innerHTML to get the value per row). "hidden-field-id" and "hidden-button-id" are client ids for hidden field and submit button - you should use Control.ClientID to get actual control ids if those are server controls.
JSON is not for that purpose, it is to pass objects serialized with a nice light weight notation, is you need to stream dinamically generated html using ashx, response.Write is what you have. You may want to take a look at MVC
Or you could use jquery if it's just html, the simpliest would be the load function, or you can look into Ajax with jquery. Since the ashx can be served as any resource it can be used in the load function.
I agree with #p.campbell and #R0MANARMY here. UpdatePanel could be the easiest approach here.
But then like me, if you don't want to go the UpdatePanel route, I don't see anything wrong with your approach. However, generating the html dynamically (entirely) at the back end is not a route I'll personally prefer (for the maintainence reasons). I'd rather prefer implementing a solution that will keep the design separate from the data.
1) A while ago I’ve started learning Asp.Net, but then I’ve heard that Ajax is “the new thing”. Since I don’t want to throw away the time I’ve invested into Asp.Net, I’d like to know if it is a common/recommended practice to use both technologies ( Asp.Net and Ajax) when creating websites and web apps in general?
2) If it indeed is a common practice to use the two technologies together, is that only true for server-side Ajax and Asp.Net or can client-side Ajax also be used in conjunction with Asp.Net?
thanx
EDIT:
A)
The only problem is that it can be a
bit trickery to do ajax request using
jquery when using asp.net
webforms(asp.net mvc was designed with
frameworks like jquery in mind so it
is easier to do).
Are you implying that perhaps jquery could be too much of a hassle when used together with webforms and thus I should think of using Asp.Net Ajax instead?
B) Little I read on ajax is that it also needs to call web services or some other technology that provides similar functionality to web services. If true, which technology do you use ( WCF or Asp.Net web services or … )?
C) Is Ajax a subsection of jquery? Thus, to understand Ajax, will I need to purchase only a book on jquery or will I also need to read a book with Ajax in its title?
You can use both, and it is common to use both. MS has a toolkit around using AJAX on asp.net sites:
http://www.asp.net/ajax/
1) Yes it is common to use Ajax and Asp.net on the same website. I do it all the time(in fact if you turn off javascript on my sites they won't work too well as so much is AJAX). AJAX allows for requests to the server to be made without refreshing the page you still need a serverside language to do stuff with that request. You also need the load the page for the first time so asp.net controls still are needed and in fact if your using asp.net ajax then you can use update panels where you put controls into that automatically become ajax enabled.
2) I am not sure what you mean but Ajax is mostly javascript so it lives on the client side and sends requests to the server side.
Edit
Ok I skimmed most of the stuff in those chapters. AJAX server side is where most of the rendering is done on the server side. So the update panel is an ajax server side control. You drag it on to your webform throw some other server side controls into it and a button. If a user then clicks on that button in the update panel an ajax request is made to the server and you can grab all the stuff you need and use C# to change it. You never have to write one line of javascript code to make that happen.
Of course that has a price though for instance an update panel does not do a true ajax request because of the page life cycle. If you actually watch the code through the debugger you will notice it will go through the page life cycle but in the end will just rerender that update panel so there is a bit more over head then if you did it yourself.
Client side Ajax is basically Microsoft trying to make it easier for you to do javascript by trying to make it more like C# syntax and giving you built in methods. A problem is that alot of people throw the buzz word Ajax too often around and call stuff that should not be called Ajax when it should be just called javascript.
This seems to be the case with this client side ajax as most of what I seen in the client side ajax chapter is almost all javascript. Like in "Figure 33.8. Selecting a menu item." all it seems to be is your click on a choose then it displays the name of that button that is not really Ajax.
Ajax to me is when you actually make a server request to post or get some information with out the page refreshing(ie full post back). For example if you got a form of data that you want to send to the server to be saved in a database. If you would hit the save button and that form data would be sent to the server without the page refreshing then that would be an Ajax request.
Most of the stuff in the ajax tool kit is more javascript
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Calendar/Calendar.aspx
For instance the calendar control to make it select different dates it is not doing any sort of request to the server since it is all javascript so why would it be ajax if it never posts to the server?
If you would take the value in the textbox that the calendar control puts the date in and post it to the server without refreshing the page that would be an Ajax request.
Finally I would not be too worried about asp.net webforms going anywhere anytime soon. I believe the guy who wrote that article about asp.net going to dye is the guy who made Ajax or was involved some how with the development of Ajax so he is probably biased.
Besides look its been 5 years now since he posted that and asp.net is stronger then ever. Ajax still needs a server to connect to, you still need to render the initial page load with either straight html or asp.net server controls.
Edit 2
1) Yes I think jquery is better the MS ajax for a couple reasons:
It uses less resources then drag and
drop controls
It simplifies javascript alot as it
makes it easier to use(such as
selecting html controls,etc). So if
I was using MS ajax I probably still
be using jquery for the selectors it
has so it is kinda redundant to use
both unless you have a good reason
too.
The only problem is that it can be a bit trickery to do ajax request using jquery when using asp.net webforms(asp.net mvc was designed with frameworks like jquery in mind so it is easier to do).
2) You really only need to learn jquery and not even javascript. I read a javascript book in like a day then jumped into jquery without even doing on exercise in the book and never did javascript before and I had no problem doing jquery. Of course if you got javascript experience it is a plus since sometimes you will be trying to find a jquery solution when javascript already has a method for what you want to do.
Edit 3
A)
The only problem is that it can be a
bit trickery to do ajax request using
jquery when using asp.net
webforms(asp.net mvc was designed with
frameworks like jquery in mind so it
is easier to do).
Are you implying that perhaps jquery
could be too much of a hassle when
used together with webforms and thus I
should think of using Asp.Net Ajax
instead?
No I am not implying that it is too much hassle for webforms was just stating the fact that it will be a bit more tricky in certain situations then ms ajax and jquery with say asp.net mvc.
asp.net webforms was not really made for a framework like jquery and has trouble dealing with it because of it's page life cycle gets in the way. MS ajax might have it's own set of challenges though too(like everything usually does). Jquery was made in mind of to try and work across all browsers since in javascript many times you would write something that worked in IE but did not work in any other browser and I am not sure if MS ajax client side version thought about this.
B) Little I read on ajax is that it
also needs to call web services or
some other technology that provides
similar functionality to web services.
If true, which technology do you use (
WCF or Asp.Net web services or … )?
Yes this is true. This was the whole point many people including me where trying to make to prove that guy was wrong that asp.net was dying because of ajax, since you need something in the back end to make a call too.
However you can choose whatever you want. You can make a separate web service( can be a asp.net web service), you can have like static web service methods in your page load ( I never done this way) and the way I use to do it is by making a generic ajax handler.
You can't however just make a regular method in your page_load and try to call it as it has to go through the entire page life cycle.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://weblogs.asp.net/craigshoemaker/archive/2008/11/07/using-jquery-to-call-asp-net-ajax-page-methods-by-example.aspx
http://dotnetslackers.com/articles/ajax/using-jquery-with-asp-net.aspx
http://sites.google.com/site/spyderhoodcommunity/tech-stuff/usingjqueryinaspnetappswithhttphandlersashx
I have not read these tutorials but these tutorials should show you the 3 different ways you can do an ajax request to an asp.net webservice, asp.net code behind page and asp.net generic handler.
Choose what ever one you think is best. I don't know if one way is better then another and there probably are more ways to do it.
C) Is Ajax a subsection of jquery?
Thus, to understand Ajax, will I need
to purchase only a book on jquery or
will I also need to read a book with
Ajax in its title
Ajax is just part of jquery and probably won't take you long to learn. If you buy a book about jquery there will probably be like 1 chapter on it. The only down side is all the jquery books I know of are all in php.
So if your just buying it to learn the ajax part probably not worth it since they will show an entire example of how to do it with php that might be slightly different then if you did it with asp.net( mostly just setting up the server side to accept the jquery calls- see the links that I posted above).
If you want to learn jquery selectors and stuff then it does matter if the one chapter is in php since it's all client side stuff expect for the ajax part( what is client side and server side).
It's not hard to really do the ajax stuff it just knowing what path you need to choose and more how to accept stuff on the server side and return stuff from the server side.
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
The above is basically all you need to do on jquery side to send some ajax stuff. The first parameter is the path where this request should go. In this case its some php file called test. The next parameter is the the actual data sent as a json result and finally the last line is the function call back line. When the ajax post request is done that line gets called and does the actions. Data is the returned stuff you sent back from the server.
http://api.jquery.com/jQuery.post/
So I would just go through the tutorials I posted and play around with the jquery selectors. Once you done that you can decide if you want to go with jquery or not. The last thing I wanted to point out about why I like jquery is the fact that if you learn the MS ajax stuff your basically stuck with asp.net( what I have no problem with since I love .Net) but with jquery you can easily take your code or those skills of jquery and use it with php, ruby or whatever else and all the client side jquery selectors won't change by switching a different language. The only thing that will be different is the ajax stuff and even that won't be 100% different as the jquery ajax client side could will be the same.
Ajax is a methodology which can be used in conjunction with with other frameworks, such as asp.net. Asp.net will allow you to integrate javascript to implement ajax solutions.
A common implementation is to use javascript to call an asp.net webservice to perform ajax operations.
Ajax is the new "old thing" - ASP.NET MVC is the new "new thing" :-)
But seriously, you can mix all of these technologies in one web application if you want:
"classic" ASP.NET (WebForms)
Ajax (using ASP.NET Ajax controls other approaches such as jQuery)
ASP.NET MVC.
AJAX is a technique essentially added on top of an existing website to allow things to be done on that page without refreshing the entire page. Here on StackOverflow, for example, you can vote by clicking the up/down arrows via AJAX, without the page refresh you'd have seen without AJAX.
It doesn't replace ASP.NET (or any other language).
AJAX does not replace ASP.NET. They can be used together or independently. ASP.NET is more of a framework, where AJAX is a set of techniques built on top of JavaScript and HTML.
There is a framework that Microsoft has called ASP.NET AJAX. There are controls that will output JavaScript so that if you wish, you can have AJAX functionality without having to get too far into JavaScript.
However, you could also write the JavaScript by hand and use XMLHttpRequests to send requests to ASP.NET URLs and get data back.
ASP.Net is primarily a server-side technology stack which dynamically generates most of the client-side code. The out-of-the-box ASP.Net 2.0 page model is a fairly painful way to implement AJAX-enhanced user interaction (though there are techniques, such as custom handlers, that make it pretty tractable). Both the ASP.Net MVC and ASP.Net AJAX frameworks provide helpful tools for making it lest troublesome.
AJAX is commonly used to describe any asynchronous, partial-page-interaction technique to build the user interface of your application.
The server-side technology and the client side technology choices are fairly independent, though different techniques for how to work with a client side technology become attractive with different frameworks on the server.