Friday, September 18, 2009

Country State Ajax binding using ASP.Net

How to bind a State drop down list on change of country drop down list

First we need a to create simple Ajax xmlHttp object and get Which country is selected by using java script. Pass Country to server side Script/page, select all the states with in that country from Data base and pass it to client side using the same xmlHttp
(System.Web.HttpContext.Current.Response.Write("All States"))
server side page name ajaxState.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="StateTableAdapters" %>


<%@ Import Namespace="System.Data" %>


<%
        if (Request.QueryString["Country"] != null)
        {


            String Country = Request.QueryString["Country"].ToString();            StateTableAdapter obpincode = new StateTableAdapter ();nbsp;  DataTableReader Dtr = obpincode.SelectByDt(Country).CreateDataReader() ;


StringBuilder strAllStaters = new StringBuilder();


            strddl.Append(" <select id=selState' style='border: 1px solid DarkBlue; width: 150px;'>");
             strddl.Append("<option value=\"0\">");                strddl.Append("Select One");strddl.Append("</option>");

            while(Dtr.Read()) {strddl.Append("<option value=" + Dtr["Country _Id"].ToString() + ">");
strddl.Append(Dtr["Country "].ToString());strddl.Append("</option>");
}

strddl.Append("</select>");System.Web.HttpContext.Current.Response.Expires = -1;


System.Web.HttpContext.Current.Response.Write(strAllStaters);
>        }


%>
<script type="text/javascript">


function ajaxFunction() {
var xmlHttp;
               try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari


}
               catch (e) { // Internet Explorer


                   try {                       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");


                   }                   catch (e) {                       try {


                           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                       }                       catch (e) {                           alert("Your browser does not support AJAX!");                           return false;                       }                   }               }               xmlHttp.onreadystatechange = function() {                   if (xmlHttp.readyState == 4) {                       document.getElementById("divState").innerHTML = xmlHttp.responseText;                   }


               }               var OId = 0;


               if (document.getElementById('selCountry’).selectedIndex > 0)                   OId = document.getElementById('selCountry’).value;                              xmlHttp.open("GET", "ajaxState.aspx?CId=" + OId, true);               xmlHttp.send(null);           }</script>
Note:I am setting the respose text to innerHTML of a div (selDiv)
document.getElementById("divState").innerHTML = xmlHttp.responseText;

Thursday, September 17, 2009

Refresh Parent window from Child window after postback/Submit

set window.opener = self;
then change location window.opener.location.href ="URL"

<script language="javascript" type="text/javascript">

    function close1() {

        window.opener = self;

        window.opener.location.href = "http://URL";

        window.close();

       

    }

</script>

Filtered text field using javascript

<script type="text/javascript" language="javascript">

    function getkey(e) {

        if (window.event)

            return window.event.keyCode;

        else if (e)

            return e.which;

        else

            return null;

    }

    function goodchars(e, goods) {

        // alert(e.value);

        var key, keychar;

        key = getkey(e);

        if (key == null) return true;

        keychar = String.fromCharCode(key);

        if (goods.indexOf(keychar) != -1)

            return true;

        if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27 || key == 40 || key == 41 || key == 32 || key == 45)

            return true;

        return false;

    }

</script>


<input name="textfield5" type="text" class="pTable" id="textPrimphone" runat="server" onkeypress="return goodchars(event,'1234567890')" />

How to validate checkbox inside CreateUserwizard Control/Wizard control ?

Validate checkbox inside Wizard step
We need a custom validator and a small client side javascript
<asp:WizardStep runat="server"
AllowReturn="False">


<asp:CheckBox ID="chkterm"
runat="server"
/>I agree with the Terms and Conditions


<asp:CustomValidator ID="CustomValidatorAgree"
runat="server"
ClientValidationFunction='validatechkbox'

ControlToValidate="txtinterest" ErrorMessage="Please read and agree Terms and Conditions" ValidateEmptyText="True"></asp:CustomValidator>

</asp:WizardStep>
< script language="javascript" type="text/javascript"> function validatechkbox(obj, args) {

var controlID1 = '<%= chkterm.ClientID %>';var checkbox = document.getElementById(controlID1); args.IsValid = checkbox.checked;} </script>

Note :Set the ControlToValidate validate property of custom validator to any other controles in the formValidate checkbox inside CreateUserWizard<asp:CreateUserWizard ID="CreateUserWizard1" runat="server">            <WizardSteps>                <asp:CreateUserWizardStep runat="server">                    <ContentTemplate>


<asp:CheckBox ID="chkterm" runat="server" /><asp:TextBox runat="server" ID="txtvalidate" Text="I agree with the Terms and Conditions" ReadOnly ="true" Width="250px" ></asp:TextBox><asp:CustomValidator ID="CustomValidatorAgree" runat="server" ClientValidationFunction='validatechkbox'
ControlToValidate="txtvalidate" ErrorMessage="Please read and agree Terms and Conditions" ValidateEmptyText="True" Display="Dynamic" ValidationGroup="CreateUserWizard1" ></asp:CustomValidator>
<script language="javascript" type="text/javascript">


        function validatechkbox(obj, args) {            var controlID1 = 'CreateUserWizard1_CreateUserStepContainer_chkterm';
            var checkbox = document.getElementById(controlID1);           args.IsValid = checkbox.checked;
}</script>

How to validate ImageButton through W3C ?

This is a problem caused by W3C running validation whilst reading the HTML rendered for a simple broswer like netscape, Image button's source code render like this
<asp:ImageButton ID="IbSubmit" CssClass="class" BorderWidth="0px" runat="server" ImageUrl="~/images/img1.jpg" />
The "BorderWidth="0px" " is aproblem it wont validate through W3C .
Try the following
Right click on the project folder and Add App_Browsers folder (select it from Add Asp.NET Folder)
Right click on the App_Browsers folder and choose Add New Item and add Browser File
Its content like this

<browsers>

<browser id="NewBrowser" parentID="Mozilla">

<identification>

<userAgent match="Unique User Agent Regular Expression" />

identification>

<capture>

<userAgent match="NewBrowser (?'version'\d+\.\d+)" />

capture>

<capabilities>

<capability name="browser" value="My New Browser" />

<capability name="version" value="${version}" />

capabilities>

browser>

<browser refID="Mozilla">

<capabilities>

<capability name="xml" value="true" />

capabilities>

browser>

<browser id="w3cValidator" parentID="default">

<identification>

<userAgent match="^W3C_Validator" />

identification>

<capture>

<userAgent match="^W3C_Validator/(?'version'(?'major'\d+)(?'minor'\.\d+)\w*).*" />

capture>

<capabilities>

<capability name="browser" value="w3cValidator" />

<capability name="majorversion" value="${major}" />

<capability name="minorversion" value="${minor}" />

<capability name="version" value="${version}" />

<capability name="w3cdomversion" value="1.0" />

<capability name="xml" value="true" />

<capability name="tagWriter" value="System.Web.UI.HtmlTextWriter" />

capabilities>

browser>

browsers>