Friday, January 14, 2011

Calling C# Code Behind From Javascript

A lot of times in the life the simplest way to explain something is the best way.

If you want to call a code behind function from javascript, you can do it.

As many others have said, there are a few steps that will get you calling your code behind methods form javascript.

Here is how I got it DONE!

Steps

1.  Enable AJAX or JASON- to be honest I am not sure how this is done completely.  But once your website is hooked up with AJAX, then the rest of the steps will go smoothly.

2.  Make sure your javascript is within a page that has a script manager with  EnablePageMethods="true".

3.  Call your javascript method within a script tag within the body of the page., either directly or by referring to a .js file in your website.

4.  Reference the right method with the PageMethods.YourMethod(param1, param2, parameter3);

5.  Make sure you have a STATIC method with that name and with a
[System.Web.Services.WebMethod] tag.  I am pretty sure you can only send string to it as parameters.

 e.g.
[System.Web.Services.WebMethod]
 public static void YourMethod(string param1, string param2, string parameter3).

And that is all.

Here is the Code for all ya greedy coders.

ASPX Page



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<form id="formMasterPageSlim" runat="server" class="masterPage">
<asp:ScriptManager ID="ScriptManagerSlim" runat="server" EnablePageMethods="true" />
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolderBody" runat="server">
<script type="text/javascript" language="javascript" src="JScript1.js"> </script>


                <asp:HiddenField runat="server" ID="HiddenFieldLeadViewID" />
                <asp:HiddenField runat="server" ID="HiddenFieldCRMConnectionString" />

<script type="text/javascript">

var wooYayIntervalId = 0;
var updateLeadViewIntervalID = 0;
 var hours = zeroPad(0, 2);
 var minutes = zeroPad(0, 2);
 var seconds = zeroPad(0, 2);


 function zeroPad(num, count) {
var numZeropad = num + '';
while (numZeropad.length < count) {
 numZeropad = "0" + numZeropad;
}
return numZeropad;
 }


 function TimerHandler() {
 wooYayIntervalId = setInterval("wooYay()", 1000);
 updateLeadViewIntervalID = setInterval("updateLeadView()", 5500);
//clearInterval ( wooYayIntervalId );
 }

 function showTime() {
document.getElementById("ctl00_ContentPlaceHolderBody_ControlWidgets1_TextBoxTimer").value = zeroPad(hours, 2) + ":" + zeroPad(minutes, 2) + ":" + zeroPad(seconds, 2);
 }



 function wooYay() {
++seconds;
seconds = seconds;

if (seconds >= 60) {
 seconds = 01;
 ++minutes;
 minutes = minutes;
}

if (minutes >= 60) {
 minutes = 01
 ++hours;
 hours = hours;
}

showTime();

//setTimeout('document.getElementById("ctl00_ContentPlaceHolderBody_ControlWidgets1_TextBoxTimer").value = ""', 990000);

}

function updateLeadViews() {

}

</script>

<div class="fields">
 <center>

Widgets<br /><br />


<asp:Literal ID="LiteralTimerStart" runat="server" />
<input type="text" id="TextBoxTimer" runat="server" /><br />
<asp:Button runat="server" ID="ButtonSubmit" Text="Submit" />

 </center>
</div>

</form>
</body>
</html>





JScript1.js File

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


window.onbeforeunload = confirmExit;


function confirmExit() {

    var PanelLead = document.getElementById("ctl00_ContentPlaceHolderBody_ControlLead1_PanelLead");

    if (isVisible(PanelLead)) {

        var timer = document.getElementById("ctl00_ContentPlaceHolderBody_ControlWidgets1_TextBoxTimer").value;
        var leadViewID = document.getElementById("ctl00_ContentPlaceHolderBody_ControlLead1_HiddenFieldLeadViewID").value;
        var crmConn = document.getElementById("ctl00_ContentPlaceHolderBody_ControlLead1_HiddenFieldCRMConnectionString").value;

        PageMethods.UpdateLeadView(timer, leadViewID, crmConn);
    }

}

function isVisible(obj) {
    if (obj == document) return true

    if (!obj) return false
    if (!obj.parentNode) return false
    if (obj.style) {
        if (obj.style.display == 'none') return false
        if (obj.style.visibility == 'hidden') return false
    }

    //Try the computed style in a standard way
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }

    //Or get the computed style using IE's silly proprietary way
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }

    return isVisible(obj.parentNode)
}

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


CodeBehind .cs C# File

//Takes the strings from the javascript function and updates a Database table

[System.Web.Services.WebMethod]
        public static string UpdateLeadView(string timer, string leadViewID, string connectionString)
        {
            string[] hourMinSec = timer.Split(':');

            if (hourMinSec.Length == 3)
            {

                TimeSpan viewLength = new TimeSpan(int.Parse(hourMinSec[0]), int.Parse(hourMinSec[1]),                                int.Parse(hourMinSec[2]));

                LeadView lv = new LeadView(connectionString);
                lv.LeadViewID = Int64.Parse(leadViewID);
                lv.ViewLength = viewLength;
                lv.Save();

                return "Saved.";
            }
            else
                throw new Exception("Error parsing Timer value");

        }


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

Note:  To get an element ID for a javascript use the page.ViewPageSource method when you right click on most browsers.  Its ID will be there.

Monday, January 3, 2011

Copying Code

Adam's Blog: Copying Code: "The object of copying code is to save time. However, I have discovered by sad and repeated experience that copying code more often than not..."