Bind Data to Repeater using Ajax - c#

I want to Bind data to a Repeater on click of a particular Button.
I can do an ajax request via jQuery and call the method to bind the data, but on the page nothing is displayed.
This is the method I use to bind the data to the Repeater:
public void BindJobs()
{
if (RptClientDetails.Items.Count != 0) return;
RptClientDetails.DataSource = new JobBusiness().GetJobInfoClient(ClientId);
RptClientDetails.DataBind();
Response.Write("myresponse");
Response.End();
}
The above method is successfully called and the data retrieved by GetJobInfoClient. This is my ajax call:
function BindJobs() {
$.ajax({
type: "POST",
url: "Client/Default.aspx?action=bindJobs",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
}

You do realize that RptClientDetails is a server side control? When you are binding to it in your call to BindJobs it is binding but you are not returning the generated HTML.
You need to return the Repeater's HTML after it has been bound in your AJAX. Then in your success handler, inject the HTML into the place where you want the Repeater to be displayed.
I would recommend checking out Rick Strahl's post regarding how to do this:
jQuery and ASP.NET Article Part 2
The easiest way would be to drop the AJAX all together and use an UpdatePanel. Just wrap your Repeater and your Button with an UpdatePanel and the call will be handled by the framework and the new HTML will be injected for you. It's a little heavier than doing it the jQuery/AJAX method but it takes almost 0 code.
EG:
<!-- Your other controls -->
<asp:UpdatePanel ID="yourPanel" runat="server">
<ContentTemplate>
<!-- Your Repeater HERE -->
<!-- Your Button HERE and server side make it call your bind -->
</ContentTemplate>
</asp:UpdatePanel>
<!-- rest of your controls -->
EDIT:
If you want to render the control so that you can send it back in your response you can do:
// This will get your Repeaters rendered HTML
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
RptClientDetails.RenderControl(hw);
string yourReatersRenderedHtml = sb.ToString();
You could then return this string in the AJAX call and then use the success method to inject it into a div or some other place holder. Honestly, the UpdatePanel is far easier and I would recommend it if your looking for the easiest way to do this and are not really worried about the performance impact of using an UpdatePanel.

You should use an UpdatePanel instead of jQuery ajax.

You might want to give jqGrid a try, if your repeater is currently creating a list/table of data. It is very easy to set up, and plays nicely with ajax calls which return JSON (and probably other formats as well, like XML). In my experience, it results in better-performing and more maintainable code overall.

Related

Updating rows in a DataGrid asynchronously in ASP.NET

I'm very new to ASP.NET WebForms applications. I have an application using a DataGrid which has a DataBinding to a List of objects. When the page loaded completely, I want to add further information to each row in the DataGrid.
The process which determines the additional information for each row must run on the server side and takes about 2s per row (network access etc.). Therefore I would like my DataGrid to refresh after every row has been processed.
This means, that I want an asynchronous mechanism that loads the data while the web page is completely accessible for the user and updates the UI as soon as a row is processed on the server side.
Technically that means that I need to send a HTTP response after processing each row to the client. The client will then read the HTTP response and update the UI.
I already tried using a UpdatePanel with a ScriptManager according to this article.
The problem with this solution is, that the UI updates when the last row has been processed. This is too late. We need an UI update after each row.
I'm used to work with WPF desktop applications. In a WPF desktop application I would just use a background worker. In the ProgressReported-EventHandler I would update the Grid with the new information and invoke an IPropertyChanged notification.
How can I achieve that in ASP.NET (.NET 4.0)? Any help and web resources are highly appreciated.
You need to use an Ajax query and a WebService
place an import in your head tag
<script src="...../js/jquery.ajaxq-0.0.1.js" type="text/javascript"></script>
and place a script zone at the end of the apsx page
<script type="text/javascript">
$(document).ready(function () {
$('#<ID_GRID_NAME> tr').each(function () {
//Get customerId Key
var customerId = $(this).find("td:first").html();
if (customerId) {
$.ajaxq("interventionQ", {
type: 'GET',
dataType: 'json',
url: '<WEB_SERVICE_URL>' + customerId,
success: function (griddata) {
$(this).find("td:last").html('<span class="badge badge-important"></span>');
}
});
}
})
});
</script>
Get rid of the ScriptManager and use jQuery. Create a gridview and then you can grab that with your AJAX success method and append to an HTML table. You can create an empty table (and hide it) on the client side and then get your table rows via AJAX and append them to the table.
$.get( "Default.aspx/MethodName", obj, function ( response )
{
var content = $( $.parseHTML( response ) ).find("#divWhereYourGridviewIs");
if ( $( "#div table" ).html() == null ) {
$( "#divOnClient" ).html( content ); //this will be the first call to get the table
}
else {
var newRow = $( content ).find( "#grd tr" )[1]; //this will be for each additional row, the [1] skips the header and gets the first row.
$( "#htmlTable" ).append( newRow );
}
} );
If you have a choice between WebForms and MVC, it would be worth looking into MVC. This CoderProject page is part of a series which has useful information for doing all that you want to do and more. This page has links to some WebForms stuff.
Long story short, jQuery and jQueryUI have a lot of things like this and examples of how to do them.

ASP.NET and AJAX Embedded HTML Modification

My project has a "HUD" on the front page that lists students that are in the process of switching course plans. It does this by doing an AJAX call to a seperate .ascx page that runs some SQL statements in C# and renders the HTML. It then delivers it back to the front page to be placed into a div named "dynamic". Here's the code on the front page that calls it:
function loadDynamic() {
var ControlName = "utilities/HUD.ascx";
$.ajax({
type: "POST",
url: "Default.aspx/Result",
data: "{controlName:'" + ControlName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#dynamic').html(response.d);
},
failure: function (msg) {
$('#dynamic').html(msg);
}
});
}
This is done in order to facilitate multiple people working on the system and being able to get live updates (there's another script that re-calls the loadDynamic() function every 10 seconds, but that's irrelevant to this problem).
However, there can be quite a few students that are trying to change course plans at one time, so in order to save space on the page, we've decided to try putting in a "...and # more records" link (an < a > tag with a javascript call in the href) that would activate another javascript function to show a seperate list with all the students and hide the list with only the few students on it (this javascript function is located on the HUD.ascx page).
<script type="text/javascript">
function loadMorePending() {
this.document.getElementById(<% =pnlMorePending.ClientID %>).style.visibility = 'visible';
this.document.getElementById(<% =pnlPending.ClientID %>).style.visibility = 'hidden';
}
</script>
Now that you have the background, here's the problem:
The second code block shown above contains references to two asp:Panels, which contain the lists, located on the HUD.ascx page. When someone clicks the "...and more" link, it should simply hide one asp:Panel and show the other. However, when it goes to call the function, it throws a "Microsoft JScript runtime error: 'ctl01_pnlMorePending' is undefined". Upon further investigation (when looking at the html source after it's been rendered in the browser), even when the 'dynamic' div is populated with the data from the HUD.ascx page, it remains empty!
<div id="dynamic"></div>
While this would explain why the pnlMorePending couldn't be found, it doesn't give me any leads on how to rectify this. How am I supposed to reference something that doesn't exist on the page? I've tried substituting the panels for divs, but it still doesn't work. The problem, I think, lies in the fact that the script transfers over to the front page fine, but it doesn't run on the HUD.ascx page where it needs to. Is there a way to do this without having 2 different HUD.ascx pages and 2 different "loadDynamic()" functions (the second being called and populated into the 'dynamic' div when the "...and more" button is pressed)?
Sorry if it's a little hard to follow. First time posting and the problem is pretty in-depth.
You are missing quotes:
this.document.getElementById('<% =pnlMorePending.ClientID %>').style.visibility = 'visible';

Loading an ASP.Net page inside another ASP.Net page using Ajax

I managed to load a distinct page inside a div in another page using jquery ajax. The problem I am encountering is that when I click a button inside this sub page, it cause a postback to the whole parent page. How can I force it to just refresh the panel it resides in?
One more thing. I am not sure I am doing the right thing, but the parent page has its own form with runat=server settings, while the secondary page that is loaded inside the div has its own form. I cannot remove the form from the latter because it causes an error.
I have seen some asp.net ajax tutorials but they do not deal with loading sub pages that havbe their own .net controls. Can anyone guide me to some good tutorial?
Thanks!
You need to create a empty with an Id for example : ajaxDiv
Then you create a jquery script like this :
<script type="text/javascript">
// Called at the loading of a page
$(document).ready(function () {
//here you execute an ajax function
$.ajax({
url: 'the url to retrieve data as string ex : /Webservice/Test',
type: 'get',
async: true of false,
//if the request is successful, you load the content of your div with the strings you loaded
success: function (data) {
$("ajaxDiv").html(data);
}
});
});
</script>
the tips is to load your page into the ajax request.
OK, since you are using jQuery, let's set up that event manipulation.
I assume the following markup:
<button type="submit" id="mySubmitButtonId">Submit</button>
Then, on my page I have the following javascript:
$("#mySubmitButtonId").click(function(event) {
event.preventDefault();
// do here what you want to do instead including refresh of a section via ajax
});

Writing to SQL Server Compact database from jquery mouseup event

I'm working on an asp.net c# empty web forms project. I have a SQL Server Compact database with a single table that I want to use to store information about an elements (x,y) coordinates.
The database should be updated with the new coordinates for a particular panel when the mouseup event is triggered on that panel (a div essentially). The solution doesn't need to be ajax, submitting the page will be ok.
The problem is that there is no mouseup type of event for an <asp:Panel> element and on the other side I'm not sure how I would trigger something server-side from jQuery. Getting the coordinates using jQuery is easy enough, but what would I do from there?
Are hidden inputs ok for this? Give me your best solution - I don't need to see code, just give me a better idea of what i should be doing.
Thanks!
First check what exactly asp:Panel is getting rendered in browser by firebug, suppose it renders as div then you can use jquery's .mouseup() function and bind this event to what ever element that panel is rendered. Suppose if that asp:panel is rendered as div then look this below code for sample.
<div id="asp_panel">
Click here
</div>
$('#asp_panel').mouseup(function() {
$.ajax({
url: "HelloWorld.asmx/Hello",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}", // if your method takes any parameter pass it in here in json format.
dataType: "JSON"
success: function(msg) {
alert(msg);
}
});
});

How to make ajax update panel ? (MVC2)

I am using Telerik tree view control:
http://demos.telerik.com/aspnet-mvc/treeview
http://demos.telerik.com/aspnet-mvc/treeview/clientsideevents
What I want to do is set up this control on the left, then a "panel" on the right, that is a view that updates when the treeview is clicked.
So I want to do AJAX call to retrieve info from DB when a click is made in the tree view. Then I can update the "panel" with information on the current item.
How could I go about building this "panel" ? And any controls that are designed for ASP.NET MVC2 are better as that is what I am implementing this in. I saw something called UFRAME but it reminded me of IFRAME and thought I should probably avoid it.
Can I do this with a partial view, and then just the partial view area of the page updates ?
Thanks.
Telerik TreeView has:
OnSelect client side event that
you want to subscribe to and
issue an Ajax call when select happens
to your Asp.net MVC application controller action that
would return a PartialView which
you can then append to right panel
That's the process to be developed.
I've never used Telerik's controls in my life but based on the documentation on their page it seems that it works this way. Everything is basically the usual Asp.net MVC + jQuery except for the OnSelect client side event that you have to use. So nothing particularly complicated as long as Telerik's controls work as expected (which can be a story of its own).
Some code
Since I've never used Telerik, I still think this can be done something along the line:
You have your TreeView defined in one of your views like:
<%= Html.Telerik().TreeView().Name("ClientSideID") %>
Then use jQuery to do the rest:
$(function(){
$("#ClientSideID").bind("select", function(e){
e.preventDefault();
$.ajax({
url: "SomeURL",
data: e.item,
type: "POST",
success: function(partialView) {
partialView = $(partialView);
$("RightPanelSelector").append(partialView);
},
error: function(xhr, status, err){
// handle error
}
});
});
});
This code isn't tested but will get you started.

Categories