Call WebMethod from Javascript in ASP.NET

6. November 2009

I needed to be able to remove a session variable from javascript so this post will talk about how to call a webmethod from javascript to remove a session item.  I will be utilizing a JS file, ASP.NET page with a WebMethod exposed in it and an asp.net user control.

The basis of this is a few things:

First we need an <asp:ScriptManager> on the ASPX page with the EnablePageMethods property set to true:

Second we need to expose a static function in our ASPX code behind so it can be available to our javascript file.

Note the [WebMethod] above the function and that the function is static. This is what allows us to make it available to the javascript file.  

Please make sure to add the statement using System.Web.Services; into the ASPX page, otherwise [WebMethod] will throw an error when compiling.

Third we need a ScriptProxyManager on the ASCX control with a reference to your JS file. This will also take care of including the JS file for your control as well so there is no need to add the <script src=....> tag. Put this as the first thing in your ASCX control.

Fourth we need the code from the JS file to bring it all together:

--------------------------------------------------------------

Anywhere in your javascript you can call the ClearSessionItem() method. Such as

function MyFunction(item){
    
    ClearSessionItem("MySessionItem");
}

Also you could call it via an onclick event with an HTML element such as:

<span onclick="ClearSessionItem('MySessionItem')">Clear Item</span>

---------------------------------------------------------------
Of course you can use this concept for almost about anything.  It allows you to not have a seperate ASMX file (Web Service) in your project.  Again, the concept here allows you to call a server side method inside javascript.


Resources:

http://www.asp.net/ajax/documentation/live/Tutorials/ExposingWebServicesToAJAXTutorial.aspx
http://www.asp.net/ajax/documentation/live/ViewSample.aspx?sref=Sys.Net.PageMethod%23PageMethod.aspx
http://www.asp.net/AJAX/Documentation/Live/ViewSample.aspx?sref=Sys.Net.PageMethod/cs/PageMethod.js


Good luck...leave questions if you got them and I'll do my best to answer  

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET, Javascript ,

Show DIV ModalPopup from GridView ASP.NET

18. February 2009

I have written a previous post regarding nested modalPopups in GridViews.  You will notice I mention it's and easy and effective way to show notes, or whatever content you want from clicking on a link from within a gridview.  The disadvantage of this method is that however many rows are in your gridview you will have that many modalPopups as well on the page.  This method is nto a full modalPopup but only utilizes one DIV on the page but will handle whatever string, notes, content you want to pass to it by clicking on the link or label from within the gridview.  I will only be pasting the code that is required to make this happen and not all of the code for the entire gridview, just the necessary parts to make it happen.  Again, this is more efficient in the fact you are only using one DIV, but also depends on what your passing into the DIV.  For this example it is just some notes.  This example is in VB.NET, but can be easily be converted to C# as most of the code happens on the client side aspx page. To make this a modal popup just style out the DIV differently and then you won't have to worry about the mouse position.

Code Behind (GridView Row Data Bound Event)

Protected Sub gvTest_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvTest.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim lblNotes As New Label
            lblNotes = CType(e.Row.FindControl("lblShowNotes"), Label)

            If Not lblNotes Is Nothing Then
                If Not e.Row.DataItem("DESCRIPTION") Is System.DBNull.Value Then
                    lblNotes.Attributes.Add("onclick", String.Format("showNotes(""{0}"", event)", e.Row.DataItem("DESCRIPTION")))
                    lblNotes.Text = "Notes"
                Else
                    lblNotes.Text = ""
                End If

            End If


        End If

End Sub


ASPX Page Portion (only the template column within the GridView)

<asp:TemplateField HeaderText="NOTES">
                <ItemTemplate>
                    <asp:Label ID="lblShowNotes" runat="server" Text="Notes" onmouseover="this.style.cursor='pointer'" ForeColor="Blue"></asp:Label>
                </ItemTemplate>
</asp:TemplateField>


DIV below the GridView

<div id="divNote" style="background-color: #cccccc; padding: 5px 5px 5px 5px; width: 200px; position:absolute; border: solid 1px black; visibility:hidden;">       
</div>


Javascript Code (tested in IE7, Firefox 3.0.5 and Safari 3.2.1 for Windows)


<script type="text/javascript">
   
        function showNotes(noteString, e){
       
          
            var posx = 0;
            var posy = 0;
            e = (window.event) ? window.event : e;
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        
            var finalString = "<strong>NOTES: </strong><span onclick=\"HideNotes()\" onmouseover=\"this.style.cursor='pointer';\" style=\"color: blue;padding-left: 100px\">Close</span><br /><br />"
            finalString += noteString
        
            document.getElementById("divNote").innerHTML = finalString;
            document.getElementById("divNote").style.visibility="visible";
            document.getElementById("divNote").style.top=posy + "px";
            document.getElementById("divNote").style.left=(posx - 250) + "px";

       
        }
       
        function HideNotes(){
                   
             document.getElementById("divNote").innerHTML = "";           
             document.getElementById("divNote").style.visibility = "hidden";       
        }
       
</script>

 

Good Luck as always let me know if something is wrong or you have a different/better way.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET , ,

Show Loading Image While Page Loads - Part II

25. June 2008

This method supports server pages somewhat. Its a little harder to implement and requires more knowledge in javascript if you have to debug your code. I prefer this method, and when possible, use it often.

Define your "Content" <div> control.

<div id="divContent">
  <img src="imgLoading.gif" alt="Loading Page" /><br />
  LOADING PAGE...
</div>


Notice, this control is not positioned absolutely, nor do we have a "Loading" <div> control. That's because we will replace the contents of the control dynamically using javascript. Here is the code.

<script language="Javascript" type="text/javascript">
  var request;
  window.onload = function() {
    request = getHTTPObject();
    request.onreadystatechange = sendData;
    request.open("POST", "content.aspx", true);
    request.send(''); }
  function sendData() {
    if (request.readyState == 4) {
      showData(); } }
  function showData() {
    var div = document.getElementById("divContent");
    div.innerHTML = request.responseText; }
  function getHTTPObject() {
    var xhr = false;         
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest(); }
    else if (window.ActiveXObject) {
      try {
        xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
      catch(e) {
        try {
          xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(e) {
          xhr = false; } } }
    return xhr; }
</script>

Now you can have a server page (content.aspx) that contains textual or media data. As long as the javascript is trying to read the page, your loading content will be displayed. Unfortunately, there are serious drawbacks to this method.

This is considered cross scripting. You may be denied unless you call local static pages, have appropiate permissions, or use Internet Explorer. (Note: IE can deny you if permission levels are increased) This method is ideal for intranet environments where you control all your permissions. Another issue, if you use AJAX Controls or Javascript, your page may get confused and not function properly. So, is there another way without the limitations of the first 2 methods? Yes.

To be concluded.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Javascript