Thursday, 28 February 2013

Calling an ASP.NET C# Method (Web Method) Using JavaScript


Another title of this article would be "Say bye-bye to Postbacks". Sometimes we need to stop annoying post-backs on ASP.NET Web Pages. For example, when one click the ASP.NET button on webpage, by default page gets post-back. So, how we stop this by keeping proper code-behind method calls. Let's look at one case.
I will create a simple form having two asp.Net textboxes and a button, we will enter our name and address in the textboxes and by clicking button will call the code-behind methods. For this we need to take the advantage of PageMethod and to setup PageMethod we need instance of ScriptManager on web page.
This is what we are going to create:
img1.gif
PageMethod is an easier and faster approach for ASP.NET AJAX. We can easily improve the user experience and the performance of web applications by unleashing the power of AJAX. One of the best things I like in AJAX is the PageMethod.
PageMethod is a way through which we can expose the server side page's methods in JavaScript. This brings so many opportunities; we can perform many operations without using slow and annoying post backs.
Let's create our HTML Page:
    <div>        <p>Say bye-bey to Postbacks.</p>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>        <br />        <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>        <br />        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />    </div>
Now, in the above code you can see one instance of the ScriptManager and two textboxes and a button at the end. In the button control you will see an attribute 'OnClientClick' to fire the JavaScript Method named "HandleIT()" and this JavaScript Method will call the code-behind C# page method.
Note: Remember to add a new attribute EnablePageMethods and set it to true in the ScriptManager.
Now, look at the JavaScript Code:
<head runat="server">    <title></title>    <script type="text/javascript">        function HandleIT() {
           
var name = document.getElementById('<%=txtname.ClientID %>').value;
           
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
            PageMethods.ProcessIT(name, address, onSucess, onError);
           
function onSucess(result) {
                alert(result);
            }
            function onError(result) {
                alert(
'Something wrong.');
            }
        }
   
</script></head>
In the above code, there is a "HandleIT()" JavaScript Method having two the variables, name and address. These variables will carry the values of the textboxes. Next, a PageMethod named "ProcessIT" is being called that passes the two parameters name and address and the other two parameters will contain the success result and error result. Next, the definition of these success results.
Now look at the code-behind of the C# (PageMethod):
    [WebMethod]
   
public static string ProcessIT(string name, string address)
    {
       
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
       
return result;    }
In the above code, to tell the script manager that this method is accessible through JavaScript we need to ensure two things. First this method should be "public static". Second there should be a [WebMethod] tag in the above method as written in the above code.
Remember to use the namespace "System.Web.Services" for WebMethods.
So, now we are all set to test it.
img1.gif

Tuesday, 19 February 2013

JavaScript calculation in asp.net grid

function CalculateTotalPrice(Price, Quantity, GrossTotal) {

    var LblPrice = document.getElementById(Price);
    var TxtQuantity = document.getElementById(Quantity);
    var TxtGrossTotal = document.getElementById(GrossTotal);

    if ((TxtQuantity.value == '') || (TxtQuantity.value == '0')) {
        var Quantity_ = 0;
    }
    else {
        var Quantity_ = TxtQuantity.value;
    }

    TxtGrossTotal.value = (parseFloat(LblPrice.innerHTML) * parseInt(Quantity_)).toFixed(2);
}

Wednesday, 19 December 2012

How to edit word document using Asp.Net?

How to edit word document using Asp.Net?


Problem -
 

Editing word document is not an easy task in ASP.Net, because we don't have any direct option to open server copy of word document. When we open any word document from server machine then first that document is downloaded to client machine's temp folder and then it is displayed. So if we will make any changes to that opened document then that changes will be saved in only client machine not in server machine.
 

Means the changes will not be reflected directly to server copy of word document.   
 

I have done some RND in this problem and came with one workaround. Hope this solution will help you.


Workaround-

Follow my article here -  How to edit word document using Asp.Net?


In this link, I have provided a detailed example with complete steps and code implementation.

How to disable back button of browser.

This is common requirement for all the web application to disable back button of browser after log-out. But there is no direct method or property to disable back button of browser. This only depends on browser cache or history, if browser contains any history or cache then back button will be active after log-out also.

Here I am explaining - How to disable back button of browser?

This can be possible using only after clearing history or cache of browser.
or
Don't allow browser to keep history or cache.

For this we can add this code for all the pages to which we don't want to allow cache.

Here is code-

  protected void Page_Load(object sender, EventArgs e)
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1000;
            Response.CacheControl = "no-cache";
        }



 In this code, I am written code to disallowing browser to cache the page. So that even after browsing the page browser will not keep page as cache or history.

This code should be included for all the pages.

Friday, 23 November 2012

Registering ASP.NET after IIS Installation

If the IIS web server is installed after the .NET Framework was installed, ASP.NET web pages will not work. This issue will also occur if the web server is reinstalled. The reason for this is that the ASP.NET file extensions are not being associated with the IIS mappings.

How To Fix
This can be fixed with the following procedure:
  1. Go to the Windows command prompt by opening the Start menu, select Run, type cmd and press OK.
  2. When your in the command prompt, type "%windir%\Microsoft.NET\Framework\.NET_Version\aspnet_regiis.exe" –i
  3. Then register Aspnet_isapi.dll with the following command:
    "regsvr32 %windir%\Microsoft.NET\Framework\.NET_Version\aspnet_isapi.dll"
Example for Registering .NET 2.0/3.0/3.5
"%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe" –i
"regsvr32 %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"

If you running .NET 3.0 or 3.5, you need to use the above example for .NET 2.0. This version of .NET is installed with 3.0/3.5. The newest versions do not have the aspnet_isapi.dll files in their folders. This isn’t a problem because .NET 3.0/3.5 are simply v2.0 with extensions. More appropriates version numbers for the latest Frameworks should be 2.1 and 2.2 since they don’t add a great deal to v2.0.

Thursday, 22 November 2012

User control for Textbox Date entry

.ascx code-

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DateTextBox.ascx.cs" Inherits="DateTextBox" %>

<script language="javascript" type="text/javascript">
    function isDate(txtDate, separator) {
        var aoDate,           // needed for creating array and object
        ms,               // date in milliseconds
        month, day, year; // (integer) month, day and year
        // if separator is not defined then set '/'
        if (separator === undefined) {
            separator = '/';
        }
        // split input date to month, day and year
        aoDate = txtDate.split(separator);
        // array length should be exactly 3 (no more no less)
        if (aoDate.length !== 3) {
            return false;
        }
        // define month, day and year from array (expected format is m/d/yyyy)
        // subtraction will cast variables to integer implicitly
        month = aoDate[1] - 1; // because months in JS start from 0
        day = aoDate[0] - 0;
        year = aoDate[2] - 0;
        // test year range
        if (year < 1000 || year > 3000) {
            return false;
        }
        // convert input date to milliseconds
        ms = (new Date(year, month, day)).getTime();
        // initialize Date() object from milliseconds (reuse aoDate variable)
        aoDate = new Date();
        aoDate.setTime(ms);
        // compare input date and parts from Date() object
        // if difference exists then input date is not valid
        if (aoDate.getFullYear() !== year ||
        aoDate.getMonth() !== month ||
        aoDate.getDate() !== day) {
            return false;
        }
        // date is OK, return true
        return true;
    }
    function checkDate() {
        // define date string to test
        var dt = document.getElementById('<%=TxtDate.ClientID %>');
        var txtDate = document.getElementById('<%=TxtDate.ClientID %>').value;
        // check date and print message
        if (isDate(txtDate)) {
            return true;
        }
        else {
            alert('Invalid date format!');
            dt.value = "";
            dt.focus();
            return false;
        }
    }

  

</script>

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox ID="TxtDate" runat="server" OnTextChanged="TxtDate_TextChanged" OnChange="checkDate();"></asp:TextBox>
<cc1:MaskedEditExtender ID="med" runat="server" TargetControlID="TxtDate" ClearTextOnInvalid="true"
    AutoComplete="false" CultureName="en-US" InputDirection="LeftToRight" Mask="99/99/9999"
    MaskType="Date" PromptCharacter="_">
</cc1:MaskedEditExtender>
<cc1:CalendarExtender ID="ceTxtdate" runat="server" TargetControlID="TxtDate" Format="dd/MM/yyyy">
</cc1:CalendarExtender>
<asp:RequiredFieldValidator ID="Rfv_Date" runat="server" ControlToValidate="TxtDate"
    Display="None" SetFocusOnError="true"></asp:RequiredFieldValidator>

c# code-

using System;

public partial class DateTextBox : System.Web.UI.UserControl
{
    public bool boolDefault = false;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public event System.EventHandler TxtTextChanged;
    protected virtual void OnTextBoxTextChanged(object sender)
    {
        if (this.TxtTextChanged != null)
        {
            this.TxtTextChanged(sender, new EventArgs());
        }
    }
    protected void TxtDate_TextChanged(object sender, EventArgs e)
    {
        OnTextBoxTextChanged(sender);
    }
    public string TextBoxValue
    {
        get { return TxtDate.Text; }
        set { TxtDate.Text = value; }
    }
    public string Validate
    {
        set { this.Rfv_Date.ValidationGroup = value; }
    }
    public bool TxtEnabled
    {
        set { this.TxtDate.Enabled = value; }
    }
    public bool TxtReadOnly
    {
        set { this.TxtDate.ReadOnly = value; }
    }
    public bool TxtAutoPostback
    {
        set { this.TxtDate.AutoPostBack = value; }
    }
    public string TxtCss
    {
        set { this.TxtDate.CssClass = value; }
    }
    public string ErrorMessage
    {
        set { this.Rfv_Date.ErrorMessage = value; }
    }
    public bool DefaultValue
    {
        set
        {
            boolDefault = value;
            if (boolDefault)
            {
                this.TxtDate.Text = DateTime.Today.Date.ToString("dd/MM/yyyy");
            }
            else
            {
                this.TxtDate.Text = "";
            }
        }
    }
}

Textbox Date validation in javascript

JavaScript Code-

<script language="javascript" type="text/javascript">
    function isDate(txtDate, separator) {
        var aoDate,           // needed for creating array and object
        ms,               // date in milliseconds
        month, day, year; // (integer) month, day and year
        // if separator is not defined then set '/'
        if (separator === undefined) {
            separator = '/';
        }
        // split input date to month, day and year
        aoDate = txtDate.split(separator);
        // array length should be exactly 3 (no more no less)
        if (aoDate.length !== 3) {
            return false;
        }
        // define month, day and year from array (expected format is m/d/yyyy)
        // subtraction will cast variables to integer implicitly
        month = aoDate[1] - 1; // because months in JS start from 0
        day = aoDate[0] - 0;
        year = aoDate[2] - 0;
        // test year range
        if (year < 1000 || year > 3000) {
            return false;
        }
        // convert input date to milliseconds
        ms = (new Date(year, month, day)).getTime();
        // initialize Date() object from milliseconds (reuse aoDate variable)
        aoDate = new Date();
        aoDate.setTime(ms);
        // compare input date and parts from Date() object
        // if difference exists then input date is not valid
        if (aoDate.getFullYear() !== year ||
        aoDate.getMonth() !== month ||
        aoDate.getDate() !== day) {
            return false;
        }
        // date is OK, return true
        return true;
    }
    function checkDate() {
        // define date string to test
        var dt = document.getElementById('<%=TxtDate.ClientID %>');
        var txtDate = document.getElementById('<%=TxtDate.ClientID %>').value;
        // check date and print message
        if (isDate(txtDate)) {
            return true;
        }
        else {
            alert('Invalid date format!');
            dt.value = "";
            dt.focus();
            return false;
        }
    }
</script>

<asp:TextBox ID="TxtDate" runat="server"OnChange="checkDate();"></asp:TextBox>