I declared a WebMethod in my default.aspx.cs file..
[WebMethod]
public static void ResetDate()
{
LoadCallHistory(TheNewDate.Date);
}
Why must the WebMethod method be declared static?
They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them in the request (i.e. ViewState and form field values).
HTTP is stateless by default, ASP.Net does a lot of stuff in the background with ViewState, Session, etc. during a standard page request to make life easier for developers.
When a web method is called through AJAX, the page isn't sending all the necessary form data ASP.Net embeds in a page to keep track of request state because it would make web methods too slow; and if you need to do a lot of processing you should move it out to a dedicated web service instead.
You can get access to methods on the page using HttpContext.CurrentHandler which is explained in more detail here and also the current user if you need it via HttpContext.Current.User.
There's an excellent article here explaining this in more detail.
Related
How come the method called from Client-side has to be a static method? The issue i am facing is that if the method is static then I can't access my server side controls such as CheckBoxPanel.
Is there any workaround this?
The method is static so that the server doesn't need to create an instance of the Page class just to run the method.
Even if the method wasn't static, you wouldn't be able to use the controls in the page anyway, because the form data in the page isn't posted to the server when you make a PageMethod call. You need to send all the information that the method needs in the call itself.
what is the difference between Asp.net page life cycle
and Asp.net Mvc page life cycle ?
Asp.net page life cycle Simply remember SILVER U
s- Start
I-Initialization
L-Load
V- Validate
E- Event handling
R -Rendering
U -Unload
What actual difference in Mvc and Asp.net page ?
ASP.NET Page Life Cycle is totally different from webforms, there are no events like we have in web forms for example: pre render, oninit etc. whenever we request a URL the only thing happens is, an instance of a controller is crated and some action method is called of it which results in rendering the View as HTML as response in the browser.
ASP.NET MVC Page Life Cycle:
According to MSDN the following are the main steps involved in asp.net mvc page life cycle:
1) Routing
routes url to its controller and action
In ASP.NET application each asp.net page implements the IHTTPHandler interface.
This interface has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for processing the request and generating the response. So in ASP.NET application it is simple, you request for a page in the url like http://mysite1\default.aspx and then it search for that page on the disk and execute the processrequest method and generate the response.
However in MVC application it doesn’t work in that way. There is no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.
2)Url Routing Module intercepts the Request:
Whenever you make a request against an ASP.NET MVC application, the request is intercepted by the UrlRoutingModule HTTP Module.
When the UrlRoutingModule intercepts a request, the first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper object.
The HttpContextWrapper object derives from HTTPContextBase class.
3)MVC Handler Executes
MVCHandler also inherit from the IHTTPAsyncHandler. When MVC Handler executes it will call the BeginProcessRequest method of the httpAsyncHandler asynchronously.
When the process request method is called a new controller gets created. The controller is created from a ControllerFactory. There is a ControllerBuilder Class which will set the ControllerFactory.
You can create your own ControllerFactory as well but by default it will be DefaultControllerFactory. The RequestContext and the name of the Contoller will be passed to the method CreateController Method to get the particular Contoller.
4) Controller Executes
controller is called and its action called requested by user.
The Execute() method starts by creating the TempData object. TempData is a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value.
The Execute() method gets the Action from the RouteData based on the URL.The Controller Class then call the ContollerActionInvoker that builds a list of parameters from the request.
These parameters, extracted from the request parameters, will act as method parameters.The parameters will be passed to whatever controller method gets executed.
Finally It will call the InvokeAction method to execute the Action.
5)Render View Method Called
at last when we call reutrn View() Render View method is called and puts reponse on the page to be displayed.
The Controller typically either executes either the RedirectToAction Method or the RenderView Method. When you call a controller’s RenderView() method,the call is delegated to the current ViewEngine’s RenderView() method.
The WebFormViewEngine.RenderView() method uses a class named the ViewLocator class to find the view. Next, it uses a BuildManager to create an instance of a ViewPage class from its path.
Next, if the page has a master page, the location of the master page is set If the page has ViewData, the ViewData is set. Finally, the RenderView() method is called on the ViewPage.
Abstract Explanation Diagram:
In Depth Diagram:
Request Flow"
Here is the asp.net mvc request flow:
Reference Links
For Understanding in details refer to Understanding of MVC Page Life Cycle
Also Here is another good article explaining MVC Page Life Cycle
ASP.NET Web Forms
ASP.NET Web Forms use Page controller pattern approach for rendering
layout. In this approach, every page has its own controller, i.e.,
code-behind file that processes the request.
In order to achieve stateful behavior, viewstate is used. Purpose was
to give developers the same experience of a typical WinForms
application.
ASP.NET MVC
It uses Front Controller approach. That approach means a common
controller for all pages processes the requests.
ASP.NET MVC approach is stateless as that of the web. So there is no
concept of viewstate.
But in actual in MVC there is no page life cycle per se (because there is no 'page' object), but there is a request processing pipeline:
You could take help from here nice description or refer to MVC4 and page life cycle?
I need to call a webmethod of a webservice asynchronously from code behind of a web page.
In the callback function I need to bind a gridview and render it. I want to partially render that gridview in the callback function in codebehind.
How to implement that?
Is it possible to implement all these in codebehind without using javascript?
There are a couple of options, but basically you need to do something like this:
Use Visual Studio to build a proxy class to access the web service, using the published WSDL
Create an async web page, by setting Async=True in the Page directive
In the Page_Load() method of your code behind, register methods that will start and end the async web service call by creating a PageAsyncTask object and calling RegisterAsyncTask()
From the method that starts the async task, call the Begin method that was created as part of the proxy class, and return the associated IAsyncResult to the caller
When the web service call completes, the runtime will call your registered end method. From there, call the End method in the proxy to get the results of the call.
Databind the results to a GridView on your page.
In case it helps, I walk through a detailed example along these lines in my book, including sample code: Ultra-Fast ASP.NET.
You can use ASP.NET asynchronous page load for that.
In general, it consists of adding Async="true" to the page directive and adding some event handlers in the code behind.
Great resource about this subject is the "Asynchronous Pages in ASP.NET 2.0" MSDN Magazine article.
I need to implement a custom handler for MVC that gives me the first look at URLs requests to determine if it should rewrite the urls before submitting the URL to the routing engine. Any pattern is a candidate for the redirect, so I need to intercept the URL request before the standard MVC routing engine takes a look at it.
After looking at a whole bunch of examples, blogs, articles, etc. of implementing custom routing for ASP.NET MVC, I still haven't found a use-case that fits my scenario. We have an existing implementation for ASP.NET that works fine, but we're returning the "standard" handler when no overrides are matched. The technique we're currently using is very similar to that described in this MSDN article: http://msdn.microsoft.com/en-us/library/ms972974.aspx#urlrewriting_topic5 which says "the HTTP handler factory can return the HTTP handler returned by the System.Web.UI.PageParser class's GetCompiledPageInstance() method. (This is the same technique by which the built-in ASP.NET Web page HTTP handler factory, PageHandlerFactory, works.)".
What I'm trying to figure out is: how can I get the first look at the incoming request, then pass it to the MVC routing if the current request doesn't match any of the dynamically configured (via a data table) values?
You would need to:
Not use the standard MapRoute extension method in global.asax (this is what sets up the route handler).
Instead, write your own route subtype, like this.
Although I explained to Craig I may not need to override scenario any more (favoring the future rather than the past), I realized there is an easy and reasonably clean place this override could be implemented - in the Default.aspx code behind file. Here's the standard Page_Load method:
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
As you can see, it would be very easy to stick a url processing interceptor in front of the MVC handler. This changes the standard default page behavior and would need to be reflected in any other MVC app you'd want to create with this same method, but it sure looks like it would work.
I have a custom security principal object which I set in the global.asax for the current thread and all is well, no problems normally.
However, I'm just adding a dynamic image feature by having a page serve up the image and whenever that dynamic image page is loaded the System.Web.HttpContext.Current.Session is null in global.asax which prevents me from setting the security principal as normal and cascading problems from that point onwards.
Normally the Session is null in global.asax only once during a session at the start when the user logs in, afterwards it's always available with this single exception.
The dynamic image page is loaded when the browser comes across an image tage in the original page i.e.
I'm guessing that this is some aspect of the fact that the browser is requesting that page without sending some credentials with it?
Any help would be greatly appreciated.
John,
I'm assuming you're using an ashx handler for the handler. If so, be sure to derive from IRequiresSessionState for example:
public class Images : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{ }
If you're not using an ashx can you describe what you mean by dynamic image page?
Josh
in Global.asax.cs Session_Start() and Session_End() you need to use "this.Session" !!
The reason for this is that HttpContext is only available when there is a request that is being processed. That is why you are getting a NULL on HttpContext.Current.Session!
From Microsoft website:
"HttpContext Class: Encapsulates all HTTP-specific information about an individual HTTP request."
But don't feel bad ... i fell for this one too! :)
Session has nothing to do with being logged in or not.
What event are you overriding when you want access to the session? Session isn't available until AcquireRequestState has been fired.
For more information, see: http://msdn.microsoft.com/en-us/library/9ysfzy8h.aspx
yes you are right This happens because the object dependancy might conficts in case of other page transferance parallel which may break down the firewall between sessions