Using Ajax on a webApp - asp.net

I'm working on an application and I would like to use Ajax to partially render part of web page instead of full post back. So I use scriptManager and updatepanel but I have an error in JS sys is not defined. I took a look in generated JS code and it seems that no Ajax client side framework has been loaded by scriptmanager, no reference at scriptressource.
I created a website by using vs2010 template to test ajax and all works fine but in web.config I don't found any difference. Is it a known problem?

Solution:
After comment and uncomment different part of my code i found that is my objectdatasource which cause the problem... ObjectDataSource use function instance to retrieve business object but since i use class properties as argument of my "select" objectdatasource function i need to define current instance of my page as object instance (1) but when work is finished is also disposed by objectdatasource .... :) i stop disposing process by using event "ObjectDisposing" (2) ...
(1)
protected void OdsRecordObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
(2)
protected void OdsRecordObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e)
{
e.Cancel = true;
}
bye !

Related

Page_Load or Page_Init

Let's take a really simple example on using jQuery to ajaxify our page...
$.load("getOrders.aspx", {limit: 25}, function(data) {
// info as JSON is available in the data variable
});
and in the ASP.NET (HTML part) page (only one line)
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="getOrders.aspx.cs" Inherits="getOrders" %>
and in the ASP.NET (Code Behind) page
public partial class getOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string lmt = Request["limit"];
List<Orders> ords = dll.GetOrders(limit);
WriteOutput( Newtonsoft.Json.JsonConvert.SerializeObject(ords) );
}
private void WriteOutput(string s)
{
Response.Clear();
Response.Write(s);
Response.Flush();
Response.End();
}
}
my question is
Should it be
protected void Page_Load(object sender, EventArgs e)
or
protected void Page_Init(object sender, EventArgs e)
So we can save some milliseconds as we don't actually need to process the events for the page, or will Page_Init lack of some sorting of a method by the time it is called?
P.S. Currently works fine in both methods, but I just want to understand the ins and outs of choosing one method over the other
Basic page life cycle will answer your question Full article : http://www.codeproject.com/KB/aspnet/ASPDOTNETPageLifecycle.aspx
check same question answer : Page.Request behaviour
Either one would work, because you're essentially throwing out the page lifecycle by calling response.Clear() and response.End(). Technically you could even go as far as putting that code in prerender and it would work. By accessing the Response object you're basically going over the head of the page and cutting it off mid-stride so that you can perform a much simpler task.
I assume you simply do not want the page lifecycle at all and simply want to return JSON from this page? If so, I highly recommend implementing it as a Generic Handler (ashx). In this case you'd simply use context.Request["limit"] and context.Response.Write in your Process method. The benefit of doing this is that you don't have all the overheads of .NET preparing the page class and starting the page lifecycle, and are instead using a file intended for the task you're doing.
It is nice to understand the page lifecycle, as shown in other answers, but realistically you're not using it at all and you'd be better off moving away from the page class entirely.
Page life-cycle only has meanings in context of page elements (controls), so i don't see any differences in your case, since you don't have any other child controls in your page - this is totally irrelevant.
But here is the real question: if you don't have any rendering of html in your page (only data serialization), why you have choose to work with regular .aspx page?
Web service is ideal candidate for this scenario. And you'll be surprised how much performance improvement you'll gain in the end.
You can very well use the Page Init method. But if you have controls in your page and want to access any property of those controls then better to use the Page load event, but in your case you don't need to use page load event.
You can go through the Asp.Net Page Life cycle here to better understand which event to use.

Converting ASP.Net Web Form to User Control OnPreInit event

I'm in the process of converting an ASP.Net webform into a User control and there an event that now says
no suitable method found to override
the event code causing the compile error
protected override void OnPreInit(EventArgs e)
{
//do some stuff
base.OnPreInit(e);
}
Is there any equivalent for a user control?
The OnInit override is available. The User Control Lifecycle on MSDN should help you in determining which event to correctly override. In any case what are you trying to achieve?
No. You'll have to use Init. I cannot think of anything I've ever done in PreInit that couldn't be done in Init just as well.
http://msdn.microsoft.com/en-us/library/system.web.ui.usercontrol_events.aspx

LoadControl vs Construct ASP.Net Control

I have a question why we can only add dynamic control using LoadControl.
For example:
public partial class wucReportParam : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
wucDate() ctrl = new wucDate();
pnl.Controls.Add(ctrl);
}
}
When in the page_load method of wucDate, the child control of wucDate is null but when i use the following method:
public partial class wucReportParam : System.Web.UI.UserControl
{
public Report Report;
protected void Page_Load(object sender, EventArgs e)
{
ctrl = (wucDate)LoadControl(#"Reports\wucDate.ascx");
pnl.Controls.Add(ctrl);
}
}
In the page_load method of wucDate, the child control of wucDate is not null.
Is anyone could explain to me why asp .net don't create any child control of wucDate when i using contructor ??? Thank you
When dynamically loading a user control, it is important to ensure that the standard ASP.NET page event pipeline is initiated and progresses normally. When you use the new operator to create an instance of a user control, that user control is not properly added to ASP.NET's event system. If the events (Init, Load, PreRender, etc.) to not fire, then your control will never function properly. That is why it is necessary to use LoadControl, as that will make sure that the instance of your user control is created properly and attached to ASP.NET.
Apparently, using LoadControl with typeof (or GetType) has the same problem as using 'new' where the child controls are not initialized. Using LoadControl with a string to the ASCX file works.
Does not initialize child controls.
LoadControl(typeof(MyReport), null);
Works!
LoadControl("Report.ascx");
The initialization of the controls inside a User Control is driven by the ASCX file. Using only "new SomeControl" will not cause this initialization to run, and even if it did, all the design (markup) in the ascx file would be lost.
Remember that the class "wucDate" is only the base class which the full user control inherits from. It's not the same class as you'll get when using LoadControl("wucDate.ascx").
And to be honest, LoadControl has not much, if anything, to do with the page life cycle. That part is handled when you add the control to the container's Controls collection.
As I recall, it pertains to how ASP.NET constructs page components at run time. In ASP.NET although your pages have a class which is defined in your code-behind file, their types don't truly exist until run time. Like a page, although you have a control defined the wucDate type isn't created until it is included at run time. For this reason, the control must be loaded with LoadControl in order to both initialize the type and properly run in through the page life cycle.
This is to the best of my memory so if I'm incorrect here please let me know.

Setting focus on postback initiated by javascript

I am working with ASP.NET doing some client side javascript.
I have the following javascript to handle an XMLHTTPRequest callback. In certain situations, the page will be posted back, using the __doPostBack() function provided by ASP.NET, listed in the code below. However, I would like to be able to set the focus a dropdownlist controls after the post back occurs. Is there a way to set this using Javascript, or do I need to rig that up some other way.
function onCompanyIDSuccess(sender, e) {
if (sender == 0)
document.getElementById(txtCompanyIDTextBox).value = "";
document.getElementById(txtCompanyIDHiddenField).value = sender;
if (bAutoPostBack) {
__doPostBack(txtCompanyIDTextBox, '');
}
}
Since you're doing a full postback, you'd need to use Page.SetFocus on the server side to get the appropriate JavaScript emitted on the next page load.
Otherwise, in a pure AJAX solution - document.getElementById('id').focus() would do the trick.
i have found the solution for this one. In the code behind event handler being called for each particular item, I call the Control.Focus() as the last line. For instance, if a dropdownlist event handler is being triggered, and the next control to get focused is the zipcode text box:
protected void ddl_state_selectedValueChanged(Object sender, EventArgs e)
{
// ... here is all my code for the event handler
txtZipCode.Focus();
}
It was much easier that I what I was trying to do. I keep trying to overcomplicate things by creating Javascript on the fly that does exactly what Microsoft is already doing for me in the Framework.

At what point should I call base methods of ASP.NET events?

In ASP.NET, if I override a page lifecycle event, should I call its base method before or after doing my work? Does it even matter?
protected override void OnPreRender(EventArgs e)
{
// My code goes here
base.OnPreRender(e);
// Or here
}
Yes you should care. Let's say for a moment that you need to insert a new base class in all of those pages. To me it's easier to just go ahead and call the base methods than have to do a lot of refactoring later.
Then again, maybe you don't need to do that.
EDIT
Based on the edit to the question here's some more info:
Yes, you should care. Sometimes you want the base classes method to fire before yours (in case of constructors), and sometimes you want it to fire after yours (destructors).
It may mean the difference between whether a property or object is available or not at the time your code gets to it.
The "OnEvent" methods in the asp.net event model merely wrap the actual event calls (in this case, the "PreRender" event). So the only thing you need to decide is "do I need to call the event before or after I do my work"?
The answer is, it depends on what the code is doing as to if it should go before or after.
As another said, if it is constructor stuff it should go before. Destructor should go after. To give a more concrete example, if you have code that processes the page and loads content, fills drop downs, and fills labels and such then you would want that to happen before any code that looks at what is pre-populated and determines visibility or business rule logic that has to do with the data on the page.
I think it's a good idea to call them just on principle. It may be true that in the framework version you're currently using there's no code in the base class methods, but who knows about future versions. Also, separation of concerns would dictate that code you write that derives from Page not assume the Page class doesn't do anything but raise the PreRender event in its OnPreRender method.
There is no single rule. I can provide you an example. My ASP.net webapp uses a NHibernate transaction opened by the master page and commited/roll-backed by it when the page ends.
Well, I MUST initialize the transaction as early as possible in the OnInit method (Master has no OnPreInit like Page), otherwise user controls cannot access the transaction until Page.Load.
The same rule applies for commit. Controls may want to update objects in the last phases of their life-cycles, then I must close the transaction as latest as possible in the Unload method, or even in the disposer!
So... in my case...
void OnInit(EventArgs e) {
transaction = session.BeginTransaction();
base.OnInit(e);
}
void OnUnload(EventArgs e) {
base.OnUnload(e);
try{
transaction.Commit();
} catch {}
}
void OnError(EventArgs e) {
base.OnError();
transaction.Rollback();
}
I would suggest you a general rule: if your page's design contract involves creating and destroying resources to be used by controls between a certain event range (ie. after Load and before PreRender), init the resource as late as possible before the event is fired, and destroy it as early as possible after the final event is fired
If you're going to call the page base methods anyway, you can use
protected void Page_PreRender (object sender, EventArgs e) {...}
rather than
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
...
}

Resources