Can you do ajax on ASP.net webform without using ajax toolkit? (Please post a example link)
yes... see my example in this post
AJAX - How to Pass value back to server
This can perform much better than ASP.NET ajax, but does take longer to code.
Sure. People have been doing ajax for years before the term ajax was even coined. Jquery is a popular library that you can use to make calls back to the server without a page refresh.
Certainly you can! What I did in .NET 1.1 (before ASP.Net Ajax was released) was to define an HttpHandler to listen on calls to ajax.aspx, run the appropriate methods, and spit back out the result. I used the Prototype library to make the Ajax call, though you could use any other, or do it by hand.
I'm going by memory, but here's the code I used (for .NET 2.0, but you get the idea):
// client-side js:
var foo = new Ajax.Request('ajax.aspx',
{
method:'get',
parameters: { method: 'GetFive' },
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
// web.config:
<httpHandlers>
<!-- pre existing handlers go here -->
<add verb="GET" path="ajax.aspx" type="Fully.Qualified.Name.AjaxHandler, AssemblyName" validate="false" />
</httpHandlers>
// AjaxHandler.cs
public class AjaxHandler : IHttpHandler {
internal delegate object AjaxFunction();
private Dictionary<string, AjaxFunction> functions;
public bool IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
this.functions = new Dicionary<string, AjaxFunction>();
this.functions.Add("GetFive", delegate() {
return 5;
});
string functionName = context.Request["method"];
AjaxFunction func = this.functions[functionName];
if (func != null) {
object val = func();
context.Response.Write(val);
}
}
}
[Big note: the above is untested and not really designed well, and may not even compile, but it should give you the right idea.]
Here's a popular tool: AjaxPro.
As others have noted, you can code the entire thing yourself using XmlHttpRequest objects and javascript. But if your app will be using very sophisticated techniques, writing the code yourself becomes quite tedious. The tools have become much more powerful and easy to use.
Parenthetically, there are two elements to ASP.Net Ajax. One is the Ajax Extensions that are included in Visual Studio 2008 and can be added to Visual Studio 2005. This can be used for much more functionality than the "toolkit". Things like partial page refreshing and retrieving data without performing a full postback. The other is the Ajax Control Toolkit, which is a separate download. The "toolkit" primarily includes fancy controls, especially ones with DHTML effects (show, hide, mimic animation).
Oh absolutely.
There are libraries such as jQuery that you can use in your ASP.NET forms instead of UpdatePanel and all the paraphernalia that surrounds it.
Where I used to work we were doing AJAX long before there was a word for it. This was in the days when our stuff only used to work in IE :-)
One thing you need to do in ASP.NET forms where you're using ASP.NET server controls is use the correct client ID that the server generates for your controls when referencing them from javascript. So if you have a label with an ID of say 'telephoneNumber', you need to reference it as <%=telephone.ClientID %>. e.g.
$("#<%=telephoneNumber.ClientID %>").attr("disabled", "disabled");
With libraries such as jQuery you can still call your ASP.NET webservices but you're probably better of investigating WCF and JSON serialisation.
You don't have to throw away everything in the ASP.NET ajax bits, I still make calls to web services using script services. It's a half way house until I can replace with JSON:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
Ajax just means while user is looking at your web page, with javascript, go back to the server and fetch something else. Then update the page with what you fetched, using javascript, the DOM.
The XMLHttpRequest object is nice, but even before it, you could do the same thing using a hidden IFRAME....
Here is all the javascript code you need to get started:
function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
// do something with xmlHttp.responseText
}
}
function SendAsyncHttpRequest()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
return
}
var url = "http://YOUR_URL"
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
YES!
There are a "gazillion" alternatives to ASP.NET AJAX out there. Most of them are better in fact too. You might want to check out my project; Ra-Ajax for your needs :)
Related
I am new to Sitecore and .NET. I got an old existing project which is based on Sitecore 6.5 and rendered content by XSLT with .NET Framework 3.5.
Now what I need to create a page that can make an AJAX call so that the page need not to be refreshed and new content can be generated. I am quite familiar with AJAX call with PHP, yet I am quite confused on those in .NET.
I googled and found most of the tutorial are based on Razor view rendering.
Can anyone provide me a full picture that how can I do to meet my objective?
I wonder if the following steps are correct:
Create a .xslt for rendering different content based on matching the URL parameter that passed into
Create a .ashx to get the .xslt content
JavaScript AJAX call to the .ashx and convert the xml content to HTML
Any examples that I can follow?
Thanks!
============================================
Update:
I tried the above flow and can print Hello World by AJAX successfully.
However, I am not sure how to get the content from XSLT in the following .ashx file with different parameter?
And are there any HttpPost/IsPostBack that can help to check if the .ashx is visited by a POST method?
I finally solved the question with the following steps.
Create a .ashx to render the sitecore content.
I have compared with .ashx, .aspx and .asmx. Seems .ashx is the best choice.
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MYPROJECT.Web
{
/// <summary>
/// Summary description for AjaxTest
/// </summary>
public class AjaxTest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string ID = context.Request.QueryString["ID"];
Database master = Factory.GetDatabase("master");
Item source = master.GetItem("/sitecore/content/Home/MYPROJECT/gallery");
Item[] items = source.GetChildren().ToArray();
context.Response.Write(items[ID].Fields["image"].Value);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
p.s I removed some validation codes from above.
JavaScript AJAX call to the .ashx.
$j('#ajax_test').click(function(){
$j.ajax({
//type: 'POST',
url: '/AjaxTest.ashx?ID='+$j('#inputunmber').val(),
//dataType: 'html',
//data: form.find(':input').serialize(),
success: function( response ) {
$j('.test_result').append(response);
},
error: function (xhr) {
alert("Error:" + xhr.responseText);
}
});
});
I have this situation:
A page with an accordion with 2 tabs, one has a list of paymentmethods, the second has a summary of the order with orderlines, amounts and totals (rendered as partialview). Selecting a paymentmethod causes the order totals to be recalculated, extra costs etc might apply.
What is the recommended way to display the new ordersummary after a paymentmethod is selected, using AJAX?
Doing an AJAX call and getting all the new amounts, orderlines, etc and setting these values using JS seems inefficient to me. Ideal situation would be if I could make an AJAX call with the selected payement method and this call would return the HTML which I can use to replace the old summary.
Is it bad to render a partialview to HTML on the server and return it using JSON? What is best practice for this situation?
I have an example here:
Javascript
$("#divForPartialView").load("/HelloWorld/GetAwesomePartialView",
{ param1: "hello", param2: 22}, function () {
//do other cool client side stuff
});
Controller Action
public ActionResult GetAwesomePartialView(string param1, int param2)
{
//do some database magic
CustomDTO dto = DAL.GetData(param1, param2);
return PartialView("AwesomePartialView",dto);
}
In your action method return a PartialView([view name]).
Then you can do this with jquery:
var req = $.ajax({
type:"GET",//or "POST" or whatever
url:"[action method url]"
}).success(function(responseData){
$('targetelement').append($(responseData));});
Where 'targetelement' is a selector for the element into which you want to inject the content.
You might want to do $('targetelement').html(''); first before appending the response to the target element.
Update
Or, better yet, use .load from Rick's answer.
I have on one page a dropdownlist which I would like to use AJAX in order to populate it from a XML file. Is there a way to tell AJAX to run only certain asp.net method without using WebServices? Any other solution is welcome but the only restriction is that it would be made on the server side (and not with js for example)?
thanks!
This is possible through a variety of means - one approach is to use jQuery on the client-side to generate the AJAX request like so (binding to the page ready here, but it could be bound to the SELECT change event):
$(document).ready( function () {
$.get('/target-url.aspx?someparam=somevalue', function(data) {
// process the returned data - dependant on the format - assuming JSON here.
var items = data['items'];
// may wish to clear the contents of the SELECT box.
// spin through and add OPTION elements
for(var i = 0; i < items.length; i++) {
$('#selectid').append('<option>'+items[i]+'</option>');
}
}
}
Where selectid is the ID of the dropdownlist element (use the ClientId if in ASP.NET).
Then you need to write some code in ASP.NET to respond to the AJAX request with your desired logic.
Some useful links:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/append/
See here for an example of using jQuery and ASP.NET with JSON:
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/
Is there a way for the Flex app to get any information about the HTML document via the ExternalInterface? Can Flex find out if a particular DIV exists, for example?
ExternalInterface is a Javascript interface with the containing page, so anything that is possible in javascript is possible through ExternalInterface, either directly or through functions on the hoast page.
AnnonymousFunctionCall from ExternalInterface
Is there a way for the Flex app to get any information about the HTML document via the ExternalInterface?
Check out JSInterface - JavaScript API for ActionScript 3. Two front page examples are called:
JavaScript'ing Inside Flash
ActionScript'ing Inside HTML
I use this library currently and it is extremely powerful. I asked him (Oleg Galaburda) once whether or not I should use this for simply being able to resize the swf. He said something like "if you only need to do a few in javascript, just stick with ExternalInterface. If you need access to the DOM in ActionScript, use this".
There are hundreds of examples in the svn repository. He's done an awesome job with this thing. It converts JavaScript Objects to ActionScript and back, so you can use full-on classes. It would take a ton of work to rebuild that so it's cross browser and everything. He's done that!
Everything in JSInterface is basically a dynamic class, so you can drill down the DOM easily. Here's some sample methods (in ActionScript):
protected function testCSS():void
{
var styleTag:JSHTMLElement = JSInterface.pushCSS('.text{font-weight:bold;color:#ff00ff;font-size:90;text-decoration:underline;}');
var font:JSHTMLElement = JSInterface.document.createElement('font');
font.innerHTML = 'Hello world!';
font.setAttribute('class', 'text');
font.className = 'text';
JSInterface.document.body.appendChild(font);
trace(styleTag);
}
protected function insertIFrame():void
{
var body:JSDynamic = JSInterface.document.getElementsByTagName('body')[0];
var frame:JSDynamic = JSInterface.document.createElement("iframe");
frame.width = 300;
frame.height = 300;
if (JSInterface.navigator.appName.indexOf('Microsoft')>=0)
{
frame.onreadystatechange = function():void
{
trace(frame.readyState);
};
}
else
{
frame.onload = function():void
{
trace('iFrame loaded');
};
}
frame.src = 'http://actualwave.com';
body.appendChild(frame);
}
The library internally uses ExternalInterface to handle everything. But to serialize/deserialize the DOM to/from ActionScript, that's a ton of work. This library should do the trick.
Hope this helps,
Lance
Responding to another question I explained how ExternalInterface actually works. What you can take from that is a simple "yes".
[edit] some sample code:
var jsFunc:String = 'function () { return document.getElementById("test") != null; }';
var divExists:Boolean = ExternalInterface.call(jsFunc);
should clarify things ...
I been waiting for sometime now to bring my Asp.net Preview 4 project up to snuff, totally skipping Preview 5 just because I knew I would have some issues.
Anyhow, here is the question and dilemma.
I have a few areas on the site which I have an ajax update type panel that renders content from a view using this technique found here. AJAX Panels with ASP.NET MVC
This worked fine in preview 4 but now in the beta I keep getting this ..
Sys.ArgumentNullException: Value cannot be null Parameter name eventObject
It has been driving me nuts...
My code looks like this
<% using (this.Ajax.BeginForm("ReportOne", "Reports", null, new AjaxOptions { UpdateTargetId = "panel1" }, new { id = "panelOneForm" })) { } %>
<div class="panel" id="panel1"><img src="/Content/ajax-loader.gif" /></div>
<script type="text/javascript">
$get("panelOneForm").onsubmit();
</script>
so basically what its doing is forcing the submit on the form, which updates panel1 with the contents from the view ReportOne.
What am I missing? Why am I getting this error? Why did they go and change things? I love MVC but this is making me crazy.
Unfortunately, just calling submit() won't fire the onsubmit event so the MVC Ajax script won't run. When the browser calls onsubmit() for you (because the user clicked the submit button), it actually provides a parameter called event (which you can see if you look at the Html outputted by the Ajax helper).
So, when you call onsubmit() manually, you need to provide this parameter (because the MVC Ajax code requires it). So, what you can do is create a "fake" event parameter, and pass it in to onsubmit:
<% using (this.Ajax.BeginForm("ReportOne", "Reports", null, new AjaxOptions { UpdateTargetId = "panel1" }, new { id = "panelOneForm" })) { } %>
<div class="panel" id="panel1"><img src="/Content/ajax-loader.gif" /></div>
<script type="text/javascript">
$get("panelOneForm").onsubmit({ preventDefault: function() {} });
</script>
The important part is the { preventDefault: function() {} } section, which creates a JSON object that has a method called "preventDefault" that does nothing. This is the only thing the MVC Ajax script does with the event object, so this should work just fine.
Perhaps a longer term fix would be if the MVC Ajax code had a check that simply ignored a null event parameter (wink #Eilon :P)
Having some irritating problems relating to this issue. Hope someone here can help me out.
var event = new Object();
function refreshInformation(){
document.forms['MyForm'].onsubmit({preventDefault: function(){} });
}
This is my current code, it works fine for updating the the form. Problem is the "var event" disrupts all other javascript events, if I have for example this:
<img src="myimg.gif" onmouseover="showmousepos(event)" />
its not the mouse event that's sent to the function, instead it's my "var event" that I must declare to get the onsubmit to function properly.
When using only onsubmit({preventDefault: function(){} } without the "var event" I get the Sys.ArgumentNullException: Value cannot be null Parameter name eventObject
I've also tried using submit() this does a full postback and totally ignores the ajaxform stuff...at least in my solution.
Hmm...I realize this might be a little confusing, but if someone understands the problem, it would be great if you had a solution as well. =)
If you need more info regarding the problem please just ask and I'll try to elaborate som more.
I believe that calling someFormElement.onsubmit() simply invokes the event handlers registered for that event. To properly submit the form you should call someFormElement.submit() (without the "on" prefix).
I don't think we changed anything in the AJAX helpers' behavior between ASP.NET MVC Preview 4 and ASP.NET MVC Beta.
Thanks,
Eilon