I have a custom class library that performs validation. I want to open up this class for use within Javascript. I understand that I can easily achieve this by utilizing WebServices/WCF or by creating a function on my page with the WebMethod attribute, but it'd be nice not to have to set all that up for every project.
Ideally I'd like to just add the WebMethod attribute to my class library methods and then call them using Javascript.
Unfortunately, you will have to expose an endpoint that your Javascript function can see. In ASP.NET this is most easily done with the web method attribute that you have encountered. However, this method requires two parts the endpoint and the actual code. If you think about it, it makes sense. Javascript has no way of talking directly to a compiled .NET assembly. It must go through a type agnostic interface. One thing that you can do, and you may be doing this, is generate the .asmx file with the web method and then have that call your class library method. This will not prevent you from having the .asmx endpoint, but will prevent any duplication of the actual code. I don't have a lot of experience with WCF, but I believe that you will still need an endpoint of some sort to interface between Javascript and C#.
The WebMethod attribute has to be used from a page level method. It's not too much of a hassle though if you set your library up correctly. A WebMethod is just a static method, but if you plan to use it in multiple pages, then you most definately want to make it a WCF service. Neither of these should be difficult and the overhead is minimal.
Alternatively you could use a base Page class that all your other pages inherit from and define your WebMethod there. This class could live in class library somewhere and be used across multiple projects.
Related
I've developed an ASP.NET user control, instances of which may appear several times on a single page. Without getting into too much application detail, when the value of any one of the instances changes, all of the other instances need to be refreshed. Currently, in order to accomplish this, I'm requiring that the consuming page implement a couple of methods which iterate through each control on the form, find all the instances of my user control, and call a Refresh method in each one.
Functionally, it's working perfectly. However, I'd like to force the developer of the consuming page to implement these two methods exactly as per my requirements. I could have them implement an interface, but that doesn't provide the functionality in each method. Or I could have them extend an abstract class, but in either case (interface or abstract class) how can I force them to inherit? I need something that will trigger a compiler error if the necessary abstract class is not extended by the consuming page. Any ideas?
Thanks.
You can enforce implementation by using 'abstract methods' in C# or using the 'MustInherit' keyword in VB.NET.
In your particular case, you're expecting the developer to essentially implement 'your' code to force the refreshing and this is something I wouldn't want delegate. Without knowing too many details I would be tempted to utilise the 'Observer' design pattern or possibly the 'Mediator' using either a separate object as a controller or even applying the controlling / publishing code to the webpage. Here's a practical example of the 'Observer' in ASP.NET.
HTH
I noticed in some code that [WebMethod] attribute is used in the code-behind file of an aspx page.
But as I remember it, this attribute is used to expose Web Service and it is often seen in asmx file.
So what's the difference between these 2 usages?
Thanks.
If that method is also static, you can call that method via javascript/ajax, without a full page postback.
Note that your ScriptManager needs to have the EnablePageMethods property set to true.
Webmethods in code behind are used for AJAX calls. If you are using jquery or similar and you need to implement an ajax functionality on your page then you will have to define you method with WebMethod attribute and have to make it public static. Then only it will work.
WebMethod's concept I feel has been taken from web services. Since asp.net didn't have any defined way of handling ajax requests to method of page behind, they have extended this feature to be used for code behind methods.
Keep a watch that being public static methods you may not be able to use your page class' internal properties here. so, you will need to deal with that.
I know why runat="server" is currently required (ASP.NET why runat="server"), but the consensus is that it should not be required if you incorporate a simple default into the design (I agree of course).
Would it be possible to modify, extend, decompile and recreate, intercept or otherwise change the behavior of how ASP.NET parses ASPX and ASCX files so that runat="server" would no longer be required? For instance, I assume that a version of Mono could be branched to accomplish this goal.
In case specific requirements are helpful, the following highlights one design:
During parsing, when configured namespace tags are encountered (such as "asp"), default the element's runat property to "server"
During parsing, when configured namespace tags are encountered (such as "asp"), if the element's runat property value is available, then that value should be used in place of the default
New page-level setting introduced (can be set in the page directive or web.config) that specifies the default runat value for a specific namespace tag
I'm afraid you'd have to modify the entire page parser to accomplish this, and I don't think that's possible.
On the other hand, you should be able to create your own. See the buildProviders Element and the BuildProvider class. You should be able to create your own build provider for .aspx pages and use it to replace the built-in provider.
Unfortunately, the PageBuildProvider class used by ASP.NET is internal, and the PageParser class that it uses to parse pages is sealed. You'll be entirely on your own.
Consider that runat="server" has been in ASP.NET for a decade now, and I think you'll see that this won't change anytime soon.
You'd also lose Designer support, but maybe you don't care about that.
So far as I know, there are no hooks deep enough in the ASP.NET Page handling process that would allow this. I know of no way to override or extend the parsing or processing of actual aspx/ascx code.
While ASP.NET is fairly flexible and lets your override many default behaviors (like how ViewState is saved/loaded, where Session is stored, etc) this is not one of them.
However... technically the Page object is just another HttpHandler. You could write your handler and do anything you wanted with it. All you have to do is implement everything the Page class does and then throw in this extra functionality. :) Alternately, pull out Reflector and dig through the Page object's ProcessRequest method and see where it is actually parsing/initializing the objects declared in aspx and you might get a clue how to implement the functionality you're looking for. But I suspect you'd be wasting your time.
We've been using IScriptControl to tie javascript objects to our UserControls and ServerControls, and it's worked fine.
The problem is that ASP.NET seems to provide no method to tie a javascript object to a Page. Up to now, we've been putting plain functions in the global namespace, but I am developing a serious allergy to that practice.
It'd be easy enough to wrap our functions into a javascript class, and to include the javascript file on the page, but how to instantiate the object, how to reference it from callback events, and how to pass data to it from the code-behind, I haven't figured out.
Or rather, the methods we've been using up to now (hidden fields, emitted javascript strings, etc.), really bug me.
Anyone have better ideas?
There isn't any association between the JS file and the page, unless you build it. With script controls, the common practice to store state is hidden fields (the ACT uses this approach). The only other ways to communicate with the server is through a web service call, form posted data, or by invoking a __doPostBack (but that isn't AJAX).
You can create some base architecture to link the two together. With script controls, the server renders a $create statement to pass properties and event handlers from the server to the client; data being posted back to the server is stored in hidden variables and processed on the client (with most script libraries), so script controls and ACT hide a lot of this for you, and you would have to build some of this if you wanted to automate this. It may help to study the client-server interaction to give you ideas of what to do if you wanted to customize this.
Funny, I was thinking of the same thing for my Nucleo project (a third party library of mine) on codeplex, but I haven't yet gotten around to it.
Based on my understanding, both of them essentially do the same thing (lets us execute a server side method from JS). Are there any differences?
Also, Ajax Page Methods can be implemented either using JQuery or using ScriptManager. Which one is preferred and why??
**BOUNTY: Adding a bounty to get clear explanation of the question. Thanks **
Fundamentally, Client Callbacks and Ajax Page Methods are doing the same thing. They use an XMLHttpRequest object to send a request (usually asynchronous) to some URL, get the results of that request, then execute a callback method you've provided (callback with a lowercase c), passing the results of the request to your method.
Having said that, there is one big difference between the two approaches:
Page Methods are implemented as static methods on your page. Your page class is just a convenient container for these methods, which could really be hosted anywhere (a web service, a custom HttpHandler, etc.). Since no instance is ever going to be constructed, the client doesn't have to send ViewState data and Asp.Net doesn't have to run through the Page's lifecycle. The flip side is that you don't have access to to your Page class's instance methods and properties. However, in many cases you can work around this by refactoring instance methods into static methods. (See this article for more information.)
Client Callbacks are implemented as instance methods on your page.
They have access to other instance methods on your page, including stuff stored in ViewState. This is convenient, but comes at a price: in order to build the Page instance, the client has to send a relatively large amount of data to the server and has to run through a fair chunk of the page lifecycle. (This article has a nice diagram showing which parts.)
Apart from that, the cost of setting them up varies quite a bit and clients use them differently:
Client Callbacks require a fair amount of idiosyncratic scaffolding
code that is intimately coupled to Asp.Net (as shown in the link above). Given
the much easier alternatives we have now, I'm tempted to say that this technology is obsolete (for new development).
Calling page methods using
ScriptManager requires less setup than Client Callbacks: you just have
to pop a ScriptManager onto your
page, set EnablePageMethods = true,
then access your page methods through the proxy the PageMethods proxy.
Calling page methods using jQuery only requires you to link the jQuery library (and familiarity with jQuery, of course).
I prefer to use jQuery to access page methods because it's independent of the server framework and exposes just the right amount of implementation details, but it's really just a matter of taste. If you go with ScriptManager, its proxy makes the page method calls a little easier on the eyes, which some might consider more important.
I would say there are differences, but would tend to say do it the way you feel more comfortable with.
I have used both approaches, and having jQuery calls from the page is generally faster. I write an ashx handler that does the job the jquery call needs (query the database, process something, etc.) and call it from the page. I wouldn't use an aspx page for a jQuery call, because you're sending a lot of info that you won't need at all. The difference/ benefit of using an Ajax.Net call is that you don't need to build another page to process things, you can use the same page events to do it.
For example, if you need to fill a second drop down list using the selected value on a first one, you could use Ajax.Net to call the SelectedIndexChanged in the page code behind and when it fires go Page_Load, SelectedIndexChanged, Page_PreRender and so on. In the event method you'd query the db and fill the second ddl.
With jQuery that could be a bit different. You make your call to an ashx handler, the handler is just a server method that do the magic and return data in the form you want to have (json, array of strings, xml, etc) and fill the second ddl using javascript.
As I told you before, some people doesn't feel too mcuh comfortable with Client code and tend to do it in the server, but I always say that you need to use the correct tool for the right job, so know your tools and apply them wisely.
If you want to know more about ASP.Net, ASHX handlers and jQuery, you can read a post that I wrote about it.
Hope it helps.-
They are essentially the same. Both:
Setup a webservice for you that the javascript for the control can call.
Provide asynchronous response without involving the page lifecycle.
They are different:
Page Methods simply require that you decorate a static method with an attribute and you are done. The rest of the magic is handled by HTTP Handlers and Modules. Callbacks require you implement a few interfaces and handle the async event handlers yourself. I find them to be a little more of a pain.
Callbacks only work with certain controls. Calling page methods allows you to affect any control through custom javascript. Callbacks have a slight advantage here in that the client-side behavior is already written and fixed. With page methods you have more flexibility, though (the behavior on the client side is determined by you).
There are a few other differences, but these are the basics. My understanding is that client callbacks tend to perform as well as Page methods, but are not used as much becuase they are only available in certain situations, whereas a Page Method is always a valid avenue.
As for the ScriptManager vs. JQuery question, my feeling here is it's about taste more than anything. I like JQuery's syntax and I feel like it performs better, but in the grand scheme of things the most expensive thing is the XmlHttpRequest... after that the execution of the javascript is likely to be insignificant in difference next to that.