Replacing item databound with jquery ajax calls - asp.net

We have a very slow ASP.NET page with a repeater. It is slow because most of the processing is done in the ItemDataBound event of the repeater. All this processing just gets 2 totals to be shown in each row.
To increase the throughput, it could be a good idea to load the repeater without ItemDataBound event and without the 2 totals.
Instead on loading the page in browser, AJAX calls can be made from each row and totals can be shown asyncronously.
Can you point to any code example where this kind of solution is achieved.
Thanks!

Indeed the jQuery.ajax() call is a good option here. You can use it to call a WebMethod defined in your codebehind
As for the server side calculation, you have a couple options:
Embed the values necessary to preform the calculation into HiddenFields within each row and pass them to your webmethod via parameters in the ajax() call.
Pass a unique ID for the row using a similar method as above (HiddenField) and do your calculation based on that ID.
As for the code, it could look something like this:
$('span.show-total').hover(
function(){
// Show panel here
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: '{"uniqueId":"' + $(this).find('input[id$=YourHiddenFieldID]').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
alert(msg.d);
}
});
},
function(){
// Hide panel here
}
);

Related

ajax and user control in asp .net

I have a VB .net application in which i have an aspx page (say default.aspx). I'm loading a usercontrol (say usercontrol.ascx) in it. I need to write an ajax code in the page (in aspx page or in ascx control) which should call a method (say test()) in the user control.
$.ajax({
type: 'POST',
url: "",
data: "{'userid':" + userId + "}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
alert(data.d);
},
error: function (data) {
alert("In error ");
}
});
what I can give as url in this ajax method in order to call a method in the user control?
You can not call webmethod in usercontrol. either you have to put your webmethod inside the page or in webservice.
Pass the control name and name of your method.
For example:
url: "usercontrol.ascx/test",

Updating ASP.NET dropdown datasource from jQuery

I want to update my dropdown list datasource (get the values from the database again) but i want to do that from jQuery, there i insert/update/delete records from that same database table.
This is my dropdown list
<asp:DropDownList ID="ddl" runat="server"
AppendDataBoundItems="True"
DataSourceID="ShortCodeDataSource"
DataTextField="ShortcodeId"
DataValueField="ShortcodeId">
<asp:ListItem>Select one...</asp:ListItem>
</asp:DropDownList>
<asp:ObjectDataSource ID="ShortCodeDataSource" runat="server"
SelectMethod="GetAllShortcodes"
TypeName="Sod.Iris.Service.ShortcodeService">
</asp:ObjectDataSource>
Also, beside code that a432511 posted, you can use UpdatePanel approach.
Put your dropdown in a UpdatePanel and then just call refresh from jquery.
On this link you have example how to do this:
http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/
cheers
You need a ScriptManager with EnablePageMethods = true
Then you need a method in your page's codebehind that is decorated with [WebMethod]. That method will be responsible for the call to the database
[WebMethod]
public string GetNewData()
{
// Get Data
// maybe serialize and return
}
Then your jQuery needs to looks something like this:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetNewData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, msg) {
// Do something with data
}
});
The success callback will need to process the returned data and manually populate the control's drop down list. The other option would be to get that serialized data from a Web Service (asmx). It would function much the same.
Hope that helps!

ASP.NET: Async postback as I type in a text box

I have a TextBox control on a page that I want to use to filter a grid. I would like the TextBox control to asynchronously post back to the page as the user types in values into the text box; preferably at a certain interval (i.e. it waits 500 ms after the user stops typing before posting back.)
How can I accomplish this in ASP.net? I know that the UpdatePanel and TextBox TextChanged event doesn't give me what I need because it does not fire as the user is typing, only after the control loses focus or if the page is posted some other way.
I also don't want an autocomplete type functionality. Are there any controls that will allow me to do what I want?
You can use jQUery, fire it on keyUp() event, and set setTimeOut method before firing an ajax call.
$("#id input").keyup(function(){
var $value = $(this);
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
msgbox.css({"background-image":"none"}).html('<img src="img/ajax-loader.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
type: "POST",
url: "Default.aspx/StaticMethod",
data: "{'username': '" + $value .val() + "'}",
contentType: "application/json",
dataType: "json",
success: function(msg) {
if (msg.d != 1) {
//
}
else {
//
}
}
});
}, 200);
this.lastValue = this.value;
}//
}
});
I suppose the OnKeyUp Javascript function would best suit your needs.
Depending on what you are doing, though, this could get very costly in terms of performance...

How to force DOM modifications done in success function persist within a jQuery.Ajax() call?

I am getting a JSON object from a webMethod by the call below and I set some textBox values based on the returned objects attributes.
Problem is, just for a moment my textBoxes are populated but then immidiately they return back to empty.
Do I make a mistake or I cannot make DOM elements modifications within a success function?
Thanks.
var ajaxCallOptions = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JQuery/Chapter16-AJAX/PersonWebServices.asmx/GetPerson",
context: document.body,
data: JSONObject,
dataType: "json",
success: function(data, textStatus, XMLHttpRequest){
var myPerson = data;
jQuery("#"+"<%=txtFirstName.ClientID %>").val(myPerson.d.FirstName);
jQuery("#"+"<%=txtLastName.ClientID %>").val(myPerson.d.LastName);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('Error: '+textStatus);
} };
jQuery.ajax(ajaxCallOptions);
The returned data is:
Additional Note:
{"d":{"__type":"BusinessObjects.Person","FirstName":"Burak","Id":"001","LastName":"Ozdogan","Department":"Information Technologies"}}
and this is a function which is bound to click event in the form:
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="loadPerson($('.personId'));"/>
If your $.ajax() is fired via a submit the default behavior is likely happening, and reloading the page.
Use return false; or event.preventDefault() at the end of your submit handler if that is the case.
$('.mySubmitButton').submit(function() {
// Send ajax request
return false;
});
or:
$('.mySubmitButton').submit(function( event ) {
event.preventDefault()
// Send ajax request
});
This same technique is used for links created from <a href=''> elements when you want to prevent the default behavior, or for any other element that has a default behavior for that matter.
I suggest use of FireBug or similar to examine the content being returned by the AJAX call. Failing this, try alerting the data which is returned.
Is the data returned the expected data?
Thanks Patrick.
It worked after this modification:
<asp:Button ID="btnSearch" runat="server" Text="Search"
OnClientClick="loadPerson($('.personId'), event); return false;"/>

Getting dynamically created tags (jQuery) from ASP.NET

I have web page in ASP.NET. I have created Tree View control with jQuery. I drag items from the tree and drop into the div element.
<div id="rows" runat="server" class="droppable">
</div>
I add items to that div using .append function from jQuery.
$(".droppable").append(event.originalTarget.innerHTML);
It works like I want. But now I want to get all dropped items from ASP.NET code. I use following code:
protected void Button2_Click(object sender, EventArgs e)
{
HtmlGenericControl control = (HtmlGenericControl)Page.FindControl("rows");
Label1.Text = control.InnerHtml;
}
But it doesn't work. I've also tried InnerText function, but still nothing. I've also put the button and label controls into UpdatePanel so the page doesn't refresh and my dropped item are still in div element.
How can I get dynamically added items from ASP.NET code.
Lukas
Your append() call simply changes the DOM structure. ASP.NET has no idea you did this.
You need to store your changes into a hidden "state" field on the page, and in your code-behind pluck them out.
var droppedItem = event.originalTarget;
$(".droppable").append(droppedItem.innerHTML);
$("#myHiddenStateField").get(0).value += "," + droppedItem.id;
Code behind:
string[] droppedItemIds = myHiddenStateField.Value.Split(",");
ASP.NET will only be able to work with form elements.
So if these rows are for example (input[type=text]) you can do this:
Request.Form["rows"]
EDIT
When the user drags over the element why don't you create a new hidden input and put the relevant value inside of it. This will make it easy to grab the value from the server with the example I used above.
better yet why not use jquery's ajax on droppable's success event and record each drop via asp.net's PageMethod, then you don't have to deal with parsing html inside your droppable element.
this should get you started
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
here is an actual example i used
$('.droppable').droppable({
accept: '#dragList > li, .columnRight li',
activeClass: 'ui-state-highlight',
hoverClass: 'hoverBorder',
drop: function(ev, ui) {
$.ajax({
type: "POST",
url: "yourPage.aspx/AddDroppable",
data: "{'id':'" + ui.draggable.context.id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").html(msg.d);
}
});
}
});

Resources