Want repeater databinding after page load - c#

I am using a web service API to pull json data then convert it to Dataset and show the data into REPEATER inside page load. now my question is that is there a way i can load the page first then it will show a message like loading please wait and then all the processing like pulling the data and showing in the repeater takes place. Is there any event like that in asp.net page lifecycle.

I recommend you to change your strategy. Instead of mixing ASP server controls and their events with AJAX use classic AJAX (jQuery) + html/css instead.
Your repeater would be a simple div
<div id="DataWrapper">
<div id="loadingLabel" style="display:none;">Loading...</div>
<div id="DataContainer">
</div>
</div>
You can then use either page web method or ASMX web service (or AJAX-enabled WCF service which I personally prefer):
public static IEnumerable GetMyData(int KeyID)
{
DataTable sourceData = GetRepeaterData(KeyID);
return sourceData.AsEnumerable().Select(row =>
{
return new
{
id = row["ID"].ToString(),
someName = row["UserName"].ToString(),
someSurname = row["userSurname"].ToString()
};
});
}
In JavaScript make a function that will call this service:
//but before that call, show the loading.. label
$('#loadingLabel').show();
$.ajax({
type: 'POST',
url: '/' + 'GetMyData',
data: {'KeyID':'8'},
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 30000,
success: onSuccess,
error: onError
});
..and loop through the result in JavaScript:
function onSuccess(result)
{
var src = result.d;
for (var post in src) {
/*
here you can create an JavaScript element and assign a CSS class to it
*/
$("#DataContainer").append('<div class="myClass">'+ src[post].someName+'</div>');
}
// when loading is finished hide the loading.. label
$('#loadingLabel').hide();
}
..and CSS:
.myClass
{
border: 1px single #000000;
padding: 5px;
}
This is of course only extremely brief answer but I hope it gives you some general idea. This is very lightweight solution and you will find it much more effective than mixing ASPs repeaters and update panels etc.
To get some real numbers about the performance install the Fiddler and compare.
Also, check out this article which is very useful and contains some very helpful advices:
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

There is no event like that in the ASP.NET life-cycle, although you could contrive something with .NET controls (update panels, timers, etc.) but a more reasonable solution could be to simply use AJAX and WebMethods (of which here is an example).
You can generally omit the housing element of a server-side repeater then, too, and just populate native client-side-only HTML elements.

Related

How to use Bootstrap Timeline to display Data in ASP.NET C#

In my ASP.NET Application, I want to use the Bootstrap timeline to display an activity log in the application.I have been searching the internet a lot on how to use the Twitter Bootstrap timeline to display data in ASP.NET C# but couldn't find any. I understand the html behind it very well but don't know how to make it dynamic in fetching data.
I hope someone can please help me with ideas as to how I can solve this problem. Tutorial links will also be appreciated.
This is a link to the bootstrap timeline I am talking about.
http://bootsnipp.com/snippets/featured/timeline
Many thanks.
Make a call to your code behind page and return json. Next use jQuery or javascript to loop over that json to dynamically build the html that the timeline needs.
<ul id="myTimeline" class="timeline">
Add li tags in a loop. This would be a good use for something like Aurelia, knockout or angular. Otherwise just use javascript to append the li tags to the ul tag. The bootstrap timeline class will take care of the rest.
$.ajax({
url: "/yourURL",
data: JSON.stringify({ yourPostData }),
type: "Post",
datatype: "json",
contentType: "application/json; charset=utf-8"
}).then(function (data) {
var obj = $.parseJSON(data.d);
$.each(obj.timelineList, function(index, item) {
$("#myTimeline").append("<li>" + item.timelineText + "</li>");
});
});
Since there is alot of html that goes into each li tag this would be a good place for a template. Look into either the template tag or use:
<script type="html" id="myTemplate">
..your html

I have issue regarding ascx user control method calling by jquery

I have user control which is included in most of my aspx page. This user control shows huge data from database. Now I have decided to fetch that by jquery. I am very much familiar with jquery and how to call server side method by jquery. My problem is that I can not specify ascx file in jquery ajax post method. Like
function loadMore() {
$.ajax({
type: "POST",
url: "Left.ascx/LoadData",
data: "{PageIndex:1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
I can not call ascx code behind method by jquery because ASCX is not directly served via URL.
I cannot write even C# code for loading & populating ascx from aspx server side method dynamically because it has been used in many aspx. So now I am in problem. No easy & good idea is coming to my mind...so I am stuck. Please show me the way to achieve it. Thanks
You cannot call the ascx method directly. What you have to do is call an aspx page method and from that call the user control method. This sounded familiar so I checked. I have an answer to a similar question here:
Jquery .ajax async postback on C# UserControl
which shows the way this can be done.
It looks to me like you want to get HTML back from your response? Possibly so you can just set the contents of a div instead of having to build the html on the client. If that is the case, then make a new aspx page that contains your ascx and have the ascx databind in the page load of the aspx.

Loading usercontrols on demand under jquery tabs

I have few jquery tabs on a usercontrol that loads a separate user control under each. Each user control is unique. It all works fine right now but the overall page response is too slow. In order to improve performance I am trying to load few user controls under these tabs on demand (that is on click of tab). Possibly without post back... ajaxish.
Can anyone guide me?
I tried to follow this tutorial and this one too but did not have any success. I have attached the code for parent usercontrol.
<ul id="tabs">
<li class="active">Rewards</li>
<li id="liCoupons">Coupons</li>
<li id="liLibrary">Library</li>
<li id="liProducts">Favorite</li>
<li id="liPreferences">Preferences</li></ul><ul id="tabPanes" class="rewardsTabs">
<li>
<div class="wrapper active">
<uc:Rewards ID="wellness" runat="server" />
</div>
</li>
<li id="liCoupons">
<div class="wrapper">
<uc:Coupon runat="server" />
</div>
</li><li id="liLibrary">
<div class="wrapper">
<uc:Library runat="server" />
</div>
</li><li id="liProducts">
<div class="wrapper">
<uc:Products runat="server" />
</div>
</li>
<li>
<div class="wrapper">
<div class="preferences">
<uc:Preferences runat="server"/>
</div>
</div>
</li>
The second link you mentioned should work. You don't need to define any user controls in your markup.
<ul id="tabs">
<li class="active">Rewards</li>
<li id="liCoupons">Coupons</li>
<li id="liLibrary">Library</li>
<li id="liProducts">Favorite</li>
<li id="liPreferences">Preferences</li>
</ul>
<div id="results" class="wrapper"></div>
Each tab click will do an ajax call
$.ajax({
type: "POST",
url: "Default.aspx/WebMetodToCall",
data: data, // I wouldn't prefer passing webmethod name here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#result').html(msg.d);
},
failure: function (msg)
//error
}
});
to the web methods.
[WebMethod]
public static string Rewards()
{
return RenderControl("~/controls/rewardsControl.ascx");
}
[WebMethod]
public static string Coupons()
{
return RenderControl("~/controls/couponsControl.ascx");
}
...
Each method will render only the requested control. Also in your method you can keep or extract the viewstate depending on your needs. After rendering, the webmethod should pass back the html string to be injected into the placeholders.
If you tried this and were successful rendering one control at a time but still seeing slowness then you have some back end issues while getting the data. If your controls are data heavy I would recommend doing some server side caching.
Hope this helps.
Does your user controls rely on post-backs and view-state for there working? It will be relative easy to fetch the user control HTML to be displayed in the tab using AJAX but then post-back on that control will send the entire data to the actual page (that may not have the user control loaded). So the basic outline would be
Track the active tab using hidden variable or view-state.
Load the user control based on active tab in the early page cycle. The best bet would be init stage (not that view-state won't be available here, so you have to store active tab in hidden variable and access it via Request.Forms collection).
Give each user control a ID and it should be different from tab to tab. ID is very important for loading the view-state.
If you get corrupted view-state errors at tab switching then you need to first load the user control for the previous tab and then at later page stage (say load/prerender), unload it and load new user control for active tab.
You can use a placeholder or panel control within each tab pane to load the user control in the correct location.
Needless to say, on change of jquery tab, you need to submit your form using post-back script. After every post-back, you need to have a script to re-initialize tabs and selecting active tab.
For better user experience, put entire thing into an UpdatePanel.
perhaps use an anchor that points to the service defined below. For instance,
<li></li>
/// <summary>
/// Service used by ajax for loading social media content
/// </summary>
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ControlService
{
/// <summary>
/// Streams html content
/// </summary>
/// <param name="type">type of control</param>
/// <returns>html stream of content</returns>
[OperationContract]
[WebGet(UriTemplate = "Content?cType={cType}")]
public Stream GetContent(string cType)
{
var tw = new StringWriter();
var writer = new Html32TextWriter(tw);
var page = new Page();
var control = page.LoadControl(cType);
control.RenderControl(writer);
writer.Close();
var stream = new MemoryStream(Encoding.UTF8.GetBytes(tw.ToString()));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
return stream;
}
}
You will need to make an Ajax call in order to make this.
now you have options to call AJAX:
1 - Call via SOAP web service (ASP AjaxScriptManager referencing will be needed for every web method).
2- Call via WCF Service as the previous answer.
3 - Call via Rest service.
4- Call via Jquery ajax method but the request must going to external page like "Actions.aspx" so when you call your method an HTTPRequest will be made into Actions page then it will have the returned data within its response. $.Ajax(url,data,action,successMethod); // this is the fastest way I tried them all.
Here is what you should to do:
1- on the change tab event call your method by using the appropriate Ajax calling method from the above options.
2- from the success method use the returned data but it's better for you to use eval(data) for the DataTime objects.
here is some example explains how to make this call:
var helper = {
callAjax: function(sentData, successFun) {
jQuery.ajax({
url: "/Actions.aspx",
type: "Get",
data: sentData,
cache: true,
dataType: "json",
success: successFun
});
}
};
helper.callAjax('request=getCities&countryID=' + countryID, function (args) {
var result = eval(args); // this object will contain the returned data
var htmlData = '';
for (var i=0;i<result.length;i++){
// write your HTML code by jQuery like this
htmlData += '<div>' + result[i].title + '</div>';
}
$('#tab3').html(htmlData);
});
now at the Actions.ASPX code use the following:
protected void Page_Load(object sender, EventArgs e)
{
object _return = new
{
error = "",
status = true
};
JavaScriptSerializer _serializer = new JavaScriptSerializer();
if (!Page.IsPostBack)
{
string str = Request.QueryString["request"].ToString();
switch (str.ToLower())
{
case "getcities":
int countryID = Convert.ToInt32(Request.QueryString["countryID"].ToString());
_return = JQueryJson.Core.City.getAllCitiesByCountry(countryID).Select(_city => new
{
id = _city.ID,
title = _city.Name
});
_serializer = new JavaScriptSerializer();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/json";
Response.Write(_serializer.Serialize(_return));
break;
}
// etc........
}
If you adjust it a little with jquery, this should work:
http://blogs.msdn.com/b/sburke/archive/2007/06/13/how-to-make-tab-control-panels-load-on-demand.aspx
Or you just use the asp.net tabs.
You should go for the second link using jquery and webmethod. That way you will actually populate the tabs on demand without making you page heavy.
In my opinion, the fastest solution to your problem (but not necessarily the best long-term) is to wrap all your UserControls in a .aspx page. In this situation, you'd just have to move your parent UserControl markup to a new .aspx page, and call it via AJAX.
Assuming that you called this page something like Menu.aspx, and further assuming that you don't need any data passed into this page (that is, it can track all of its own data internally), your jQuery AJAX call would look something like this:
function GetMenu ($placeholder) {
$.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json",
url: "Menu.aspx",
done: function (result) {
$placeholder.html(result.d);
},
fail: function () {
$placeholder.html("Error loading menu.");
}
});
}
Some notes:
done and fail will replace success and error in jQuery 1.8, so any jQuery AJAX you use should plan for this transition.
I wrapped this in a function largely because I prefer to put AJAX calls inside JS classes and functions, and then reference those objects. With a menu, it's unlikely you'd have several different pages loading the same data via AJAX (since this will be on some sort of master page, I'm guessing), but it's always good to get yourself in the habit of doing these things.
Depending on your feelings about tightly-coupled HTML/JavaScript, you could replace $placeholder above with a callback function. Calling that from your the page where your menu resides would look something like:
$(document).ready(function () {
GetMenu(MenuCallback);
});
function MenuCallback(menuHtml) {
$("#menu").html(menuHtml); // I'm assuming the ID of your ul/span/div tag here.
}
Some people (myself included) use the $ prefix to differentiate between JavaScript and jQuery variables. So here, $placeholder is a jQuery variable.
You might be able to re-write this $.ajax call as a type: "GET", which would be a little bit more efficient, but I'm not sure if the UserControls would cause problems in that regard. Normally, if I'm loading an entire .aspx page via AJAX, I use GET instead of POST. You don't have to change much to try it out: just switch out the type property and change result.d to result.
I think the best solution is to implement client call back
http://msdn.microsoft.com/en-us/library/ms178210.aspx
When user clicks on some tab,onclick event calls js func with name of tab as parameter, than that tab calls server code with same parameter.
Than in code you load controls you want depending which tab is clicked.
Now you need to render controls into html and send tham back to js function.
Now you have controls in js function, find where you want to insert code an insert it.
that should work in theory and it is not to complicated :))
an asnwer (not mine) to this question is probably useful to you:
Asynchronous loading of user controls in a page
it states that there are problems with this with needing a form on the user control to post back, but that should be ok to have independent forms with ajax post. you'll have to think about what happens when posting the form(s) on the page, but shouldn't be insurmountable. shouldn't be any reason you couldn't just make it the ashx handler you have mentioned.

How to send pre-formatted HTML elements from a WebMethod to jQuery

The title sort of explains what I'm trying to do.
The reason for this is that I am trying to implement infinite scrolling on my ASP.NET C# Website. I've previous accomplished the "effect" of lazy scrolling with the ListView Control but that was a dirty and 'slow' trick that used a DataPager and a couple of HiddenFields.
I would like to send a completely pre-formatted HTML element from a WebMethod to jQuery so that I can append it on the container <div>.
Actually what I need rendered in the WebMethod is a bunch of objects inside a container <div> that are similiar to the Facebook Wall. What I previous had was a ListView (B) nested in another ListView (A). A Single Each <ItemTemplate> from a single ListView had multiple ListViewItems of the other ListView. (A) Representing a wall post and (B) Comments bound to the Primary Key of (A).
Anyway, am I looking at this issue from the right corner or should I figure out some other way of doing this? Please share you thoughts.
Thank you.
You can just return a string from your webmethod with the html in it - and then pump it directly into an html element on your page on the 'success' function. NB I think this is the 'html()' element - or you can use .append(text);
Using JQuery
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetHTMLFormatted",
data: "{}",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").html(msg.d); // or .append(msg.d);
}
});
});
});
A better way to do it though is to return a JSON structure and use a template library to emit your html structure. See http://stephenwalther.com/blog/archive/2010/11/30/an-introduction-to-jquery-templates.aspx

How can I call a non static method written in code behind using javascript?

Kindly help me to call a non-static method from code behind, using json object.
The following code is used in aspx page:
function columnDropdownScript() {
if (id == "ExpressionsLink") {
var dropdown = document.getElementById("<%=ddlTableNames.ClientID%>");
}
/
/ Configure AJAX call to server on itemChange of ddlTableNames
$.ajax({
type: "POST",
url: "Webtop.aspx/FillColumnDropdown",
data: requestTableParameters,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (id == "ExpressionsLink") {
$("#ddlColumnNames").empty();
}
}
// alert('Check Column DropDown' + msg.d.length);
},
error: DisplayError //Event that'll be fired on Error
});
}
The following code is written in aspx.cs page
[WebMethod]
public static List<string> FillColumnDropdown(string selTableName)
{
//Code to update Selected Columns in table
}
Since you want to call page's instance method I believe that you want to use other page's controls properties or features provided by an ASP.NET platform like ViewState or some other. But when you fire plain ajax request you can't use any of that possibilities.
So the only one option for you to use ASP.NET Ajax. In that case page comes through full life cycle including recreation all page's controls instances on the server, reading ViewState and so on.
Mostly for using ASP.NET you don't need any custom javascript calls because all required javascript provided out of the box.
What do you need it's just add ScriptManager and UpdatePanel controls onto the page, put your dropdown in UpdatePanel and set AutoPostback on it to true. That's all. After that you can use server-side SelectedIndexChanged event habdler of that dropdownlist and it will be fired asynchronously.
For more info about using an UpdatePanel follow this link: Introduction to the UpdatePanel Control
EDIT: by the way: if you need only the Session or Application state or Cache but no page's controls properties and no ViewState you still can use plain ajax calls and static server methods.
Actually the AJAX is quite tricky thing :)

Categories

Resources