Ajax code is faster or updatepanel is faster to populate dropdown in asp.net - asp.net

I have 20 ajax editable drop-downs in a form. Each drop-down binds with respect to other's selectedindex change.
I have lots of record coming from the database for binding, and some operations. What will perform better?
Should I use this code to bind the drop-down:
var XmlHttp;
//Creating object of XMLHTTP For AJAX Method
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
XmlHttp = null;
}
}
//Creating object of XMLHTTP in Mozilla and Safari
if (!XmlHttp && typeof XMLHttpRequest != "undefined") {
XmlHttp = new XMLHttpRequest();
}
}
function GetAppStoreLnk(id) {
var txtnameid = document.getElementById(id);
CreateXmlHttp();
var requestUrl = "Default2.aspx?id="+txtnameid+"";
if (XmlHttp) {
XmlHttp.onreadystatechange = function() { getschemename(txtnameid) };
XmlHttp.open("GET", requestUrl, true);
XmlHttp.send(null);
}
}
function getschemename(id)
{
// To make sure receiving response data from server is completed
if(XmlHttp.readyState == 4) {
// To make sure valid response is received from the server, 200 means response received is OK
if(XmlHttp.status == 200) {
var strData = XmlHttp.responseText;
if(strData != "") {
var arrscheme = strData.split("|");
id.length = 0;
for(i=0; i<arrscheme.length-1; i++) {
var strscheme = arrscheme[i];
var arrschnm = strscheme.split("~");
id.options[i] = new Option();
id.options[i].value = arrschnm[0];
id.options[i].text = arrschnm[1];
}
} else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "Scheme Name is not available";
}
document.body.style.cursor = "auto";
}
else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "server is not ready";
document.body.style.cursor = "auto";
}
}
}
Or should I go for UpdatePanel?
Which one will be the better option for me?
Or is there a better spolution?
I want very good performance as this page is used frequently by our client, and we want to make sure it is fast.
I am using vs2010.

The AJAX route will be faster. UpdatePanels make things look like partial page loads, but in fact, it returns the whole page and just updates the section inside your UpdatePanel.

UpdatePanel does not provide the efficiency that we normally associate with AJAX. Did you know, for example, that when UpdatePanel control performs asynchronous AJAX callback to the server to update its content, the request contains all the content of a publication automatically ASP. NET conventional, including status display.
An application is more effective preferring to use asynchronous calls to WebMethods or page methods instead of using UpdatePanel.
Link : http://msdn.microsoft.com/fr-fr/magazine/cc163413.aspx

I agree with the rest of the answers, the evil UpdatePanel decreases the overall performance of the page because in order to work, it must send the whole page ViewState back and forth in order to execute the whole page life cycle on every async post
With simple AJAX calls this is totally different, the calls only get the data you need and the performance is considerably better
However - danger danger DR Robinson
Since you are using WebForms and your intention is to populate 20 DropDownLists, you can try doing it with AJAX calls and you will notice that apparently that works correctly. but if you try to post your page with one value added to a DropDownList via javascript/jquery, an exception will be thrown.
This is because ASP.Net WebForms by default validates the values posted to the server, if the values are not registered in the ViewState, a security exception will be thrown because of an attempt to tamper the page content.
Sadly you cannot disable this option at control level, you would have to disable it at page level:
<%# Page EnableEventValidation="false" ....
In WebForms this is not recommended though...

Related

How to know server response in ResponseEnd method of a RadAjaxManager

Im using Rad ajax manager, RadAjaxLoadingPanel in my webform.
I have two panels in my form, Panel1 is having Create account controls and another Panel2 is for Thank you notes.
When user created an account successfully i need to hide Panel 1 and show Panel 2.
Im using ResponseEnd method to do make visible/hide using Javascript below method.
function ResponseEnd(sender, arguments) {
//hide the loading panel and clean up the global variables
if (currentLoadingPanel != null) {
currentLoadingPanel.hide(currentUpdatedControl);
}
ShowTY();
currentUpdatedControl = null;
currentLoadingPanel = null;
}
function ShowTY(){
document.getElementById('<%= Panelty.ClientID %>').style.visibility = "visible";
document.getElementById('<%= Panelty.ClientID %>').style.display = "block";
document.getElementById('<%= Panelsu.ClientID %>').style.visibility = "false";
document.getElementById('<%= Panelsu.ClientID %>').style.display = "none";
}
If user already exist or any db server error i need show Panel1 display error message in a Label
For this I need to write a condition to check whether server response succeeded or not in the above method.
Please let me know how i can know the server response or how i can handle this issue.....
Please reply soon
Thanks
According to the documentation: There is no way to pass data from an event on the server to the client side event handler.
I would suggest moving the logic to configure the display (hiding/showing elements, displaying error messages) to the server, where the code to create the account is. Since you are using the loading panels, this should be straightforward:
if(accountCreatedSuccessfully) {
Panelty.Visible = true;
Panelsu.Visible = false;
}
else {
// TODO: display the error messages somewhere, in a label
Panelty.Visible = false;
Panelsu.Visible = true;
}

adding dynamic message at end of flash video

I am working on a Flash training video. I would like at the end of the video for a message to pop up with a dynamic confirmation code. I have the code for the confirmation code, but am having trouble creating something either at the end of the flash video or within the aspx page to trigger this message. Any thoughts or ideas of how to solve this would be greatly appreciated.
Thank You.
Depend on the purpose of the application, you can do either one. One thing to consider is does the user has to go through the flash video to obtain the code. If so, you need to organize the flow of the application in a way that the user can't cheat their way to obtain the code.
The ideal way is to have the flash called aspx page at the end of the movie to obtain the dynamic code. This can be done using URLLoader in ActionScript 3.0 or LoadVars in ActionScript 2.0.
URLLoader example
//this is the data
var data = "This is data";
//url of your aspx code
var request:URLRequest = new URLRequest("http://www.yourdomain.com/GenerateCode.aspx");
request.contentType = "text/xml";
request.data = data;
//use POST method
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
try
{
//execute the request
loader.load(request);
}
catch (error:ArgumentError)
{
trace("There is an ArgumentError.");
}
LoadVars example:
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received response from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "Error!";
}
}
//this is the data
lv_out.data = "This is data";
//begin invoke aspx page
lv_out.sendAndLoad("GenerateCode.aspx", lv_in, "POST");
There another easier way but not the best practice i should say. The easier way would be to direct user to aspx page that generate dynamic code after users finish the flash movie. The negative side is, the page can be accessed although users did not finish the flash movie.

recovering from missing session state in ASP.NET MVC with Telerik Ajax

I have a webpage which includes a telerik grid in ajax mode. The data for the grid is constructed in the controller action used to serve the view, and then stored in the session. 90% of the time its available to the ajax method used to populate the grid. And sometimes its not, which is odd. Some sort of race condition ?
public ActionResult EditImage(int productModelId, int revision)
{
ViewBag.Current = "Edit";
//Unit of work and repo generation removed from brevity
var modelToEdit = prodModelRepo.Where(p => p.ProductModelID == productModelId && p.Revision == revision).FirstOrDefault();
var vmie = new VMImageEdit(modelToEdit)
{
//init some other stuff
};
Session["vmie"] = vmie;
return View(vmie);
}
Now the telerik contorol will post back to _EISelect in order to populate its grid
// Ajax Actions for EditImage
[GridAction]
public ActionResult _EISelect()
{
var vmie = (VMImageEdit) Session["vmie"];
return View(new GridModel(vmie.Colours));
}
So if my session object is null, how can I recover - I guess I need the productModelId and Revision parameters from the original EditImage call. Are they available in the _EISelect in any way - its posted to, and the post contains nothing useful.
Oh to make this possibly harder, this page will be displayed via an inline frame.
The answer lies in the telerik ajax databinding - this can be used to pass arbitrary data in the querystring
.Select("_EISelect", "AdminProduct", new { productModelId = Model.ProductModelId, revision = Model.Revision})
which can be recovered in _EISelect as parameters. Simples.

ASP.NET session in Javascript

I have the following code invoked from a button click - js event
function onOkReason() {
alert("called");
var session = $('<%=Session["A"]%>');
if (session == null) {
<%Session["A"]%> = "1";
alert("1");
}
else {
<%Session["A"]%> = null;
alert("2");
}
alert(session);
}
It does not seem to work...Any pointers as to what may be wrong...
The <% %> is evaluated when the page is processed on the server, you can't then set it from the client - it's to late, the page has been processed and sent back to the clients browser.
You'll need to post back to the server (either full or an AJAX call) to set the data.

How to automatically refresh a web-page using ASP.NET?

I have an asp.net application that would 'simulate' real-time video. I did that acquiring multiple picture from an mysql database.
The problem is how would it be displayed on the web-page.? I refresh the page 1 second per picture, the result is the pictures are choppy and flickery.
Response.AppendHeader("Refresh", "1")
How can I make the refresh rate of the page 4times per second? or is there any implementation for it to be displayed in a continent way.
I would really appreciate if you will reply. good day (^_^)...
here is the script that i am using to read the images from the database,.
If dr.Read Then
dr.Read()
Response.ContentType = "image/jpeg" 'gets or sets the type of output stream
Response.BinaryWrite(dr.Item("file")) 'writes a stream of binary characters to the
http output stream
Else
Response.Write("There is no current active webccast.")
End If
dr.Close()
create a javascript method to change the image using xmlhttpobject and recursively set a timer
function Timer() {
setTimeout("getImage(['imageContainer1'])", 200);
t = setTimeout("Timer()", 100);
}
function getImage(params) {
var request=getXMLhttpObject();
makeRequest("ajax/ObtainImage.aspx?name='myimage'+param[1]+'.jpg",request, imageResponseHandler(request, params));
}
function getXMLhttpObject() {
return (navigator.appName == "Microsoft Internet Explorer")? new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
}
function makeRequest(url,request, Handler) {
request.open("GET", url, true);
request.onreadystatechange = Handler;
request.send(null);
}
function imageResponseHandler(request,params) {
return function() {
if (request.readyState == 4)
document.getElementById(params[0]).src = request.responseText;
}
}
I would either use some Javascript/Ajax to change the content or the meta-refresh (probally not the best for fast refresh).
Maybe you need to think about loading more than one picture onto the page and using javascript to cycle between them. Rather than refreshing the page you could get the pictures using AJAX.
If you really want to simulate video, you need to be able to display at least 15 pictures each second (15fps). Making that many requests per second isn't a great idea.
If you absolutely must do this, I'd suggest "buffering" the pictures first, before displaying them, and if possible, fetching them in batches:
buffer = [] // cache loaded images
bufferSize = 30 // load 30 images before playing
function loadImage(src) {
var img = new Image()
img.src = src
buffer.push(img)
}
function animate(target) {
if (buffer.length > 0) {
var img = buffer.shift()
document.getElementById(target).src = img.src
}
}
function bufferImages() {
for (var i=0; i<bufferSize; i++) {
loadImage('/ajax/ObtainImage.aspx?name=img')
}
}
setInterval("animate('imgTarget')", 65) // should give us about 15fps
setInterval("bufferImages()", 1000) // every second
Add this to the head of your html document.
Not the most efficient way, but it will work.
<meta http-equiv="refresh" content=".25" />

Resources