Loading usercontrols on demand under jquery tabs - c#

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.

Related

Dynamically Add Views ASP.NET MVC

I've had a look over a couple of the other questions on the site and cant find anything that exactly answers what I'm looking to do. To help I'll give a bit of background.
I've recently started experimenting with ASP.NET and MVC4. As my first real attempt at building something useful I am building a web application that will allow me to record and track my workouts in the gym. I have got the basis of all my models/controllers/views etc. The part I am having trouble with is the actual layout of the page to record workouts. Each Workout is made up of a list of Sets (The sets contain information like Exercise, Weight, No of Repetitions etc.... Now the way I want this to work on the WebApp is for a user to be able to hit a button for adding a set. This will then load a a section below without a page re-load that allows them to enter information about that set. They can hit the same button again to record a second set so on and so forth....
They will then hit a save button and I need to loop through each "Set" that has been added and save the information to a database.
I think it should be possible, just not exactly sure how to achieve it. The way I would do it in a standard Windows Application is using UserControls, I am thinking maybe Partial Views in ASP.NET and MVC?
Any ideas guys?
Any more questions let me know.
We did something similar with MVC5, maybe you can figure something out from here.
We used AJAX and PartialViews, at first the page loads we load a table with some initial content, and an Add Option button. When the user hits the button, we increment the current count and add another row to the table via an action which returns a partial view.
<script>
var currentCount = 1;
$(document).ready(function () {
$("#AddOptionButton").click(function () {
var CountryOptions = {};
CountryOptions.url = "AddOption";
CountryOptions.type = "POST";
CountryOptions.datatype = "text/html";
CountryOptions.data = JSON.stringify({count: currentCount });
CountryOptions.contentType = "application/json";
CountryOptions.success = function (html) {
$("#attributesList tr:last").after(html);
currentCount = currentCount + 1;
};
$.ajax(CountryOptions);
});
});
</script>
<table id="attributesList">
<tr>
<th>#</th>
<th>Name</th>
</tr>
<tr>
<td>1.</td>
<td><input type="text" name="optionInput[0]" value="Option 1" /></td>
</tr>
</table>
<input type="button" name="AddOptionButton" id="AddOptionButton" value="Add 1 More" />
<input type="submit" value="Submit Form" />
Our partial view will get the current count as input and returns something like below
<tr id="NewRow1">
<td>2.</td>
<td><input type="text" name="optionInput[1]" value="New Option Value"/></td>
</tr>
Note that we are getting an array of optionInput when the form is submitted. We can easily save the data by looping through the inputs.
You said "without a page re-load". You can do that by using AJAX. It sounds like you have to do much fundamental education to reach your goals. I want to suggest you to work into JavaScript and understand the difference between client-side and server-side in the world of web development. In addition it is important to know the behaviour of HTTP (requests, responses, etc..).
After that, you are able to load content from the server asynchronously using and ajax request. You can do that easily using jQuery. Example here:
$.ajax({
type: 'post',
url: '/Controller/Action',
data: {CustomerName: 'James', AdditionalData: ... },
dataType: 'JSON',
success: function() {
// do anything after request success
}
});
With JavaScript you are able to create an communication between server and client and manipulate the DOM of the client.

Want repeater databinding after page load

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.

Executing Server-Side Methods by Clicking on a DIV

I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work

asp:dropdownlist change dynamically

Is there any chance, when I select a row from asp:dropdownlist, dynamically change page, execute sql query and after result, change selected row in second asp:dropdownlist?
If this isn't possible only with asp.net and codebehind, please let me know how to execute SELECT-query in javascript (may be with Ajax; but I don't understand it) and change second dropdown's selected row.
Thanks!
Its a bit of a generic question because there is a couple of options that you could do plus I'm not 100% sure what you want to do. In short you could use AJAX to contact a PHP page which will do an operation on your database. A result it generated and sent back to the client. You could use JSON to hold the data that is getting sent to the browser.
All AJAX does is allow you to get data from another location based on the URI you give. I would use the JQuery library as it makes it easy to implement AJAX.
// This will trigger ajax whenever the is a change in the drop down. I am assuming the drop down class is .dropdown
$('.dropdown').change(function() {
$.ajax({
type: "POST",
url: "page_change.php",
data: { name: "about_us" }
dataType:JSON,
success: function(data) {
//The data returned from test.php is loaded in the .result tag
$('.result').html(data.html);
// If you want to change page you would execute
window.location(data.url);
}
});
});
page_change.php will then contact your database and generate JSON.
More information about JQuery AJAX here:
http://api.jquery.com/jQuery.ajax/
You will need to look at JQuery, AJAX, PHP and JSON to change data on your page.
If you just want to change page on a drop down change I suppose you could store the page name in the option id?
$('.dropdown').change(function() {
var page = $(this).attr('id');
window.location(page + ".html");
});

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

Categories

Resources