April 28, 2011

Asp.net DropDownList Selected Value with Jquery

Here's final code



<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="js/JScript.js" type="text/javascript"></script>

    <script type="text/javascript">      



        function btnClick() {



            var countryCode = $('#ddlCountry').val();

            var countryName = $('#ddlCountry').find('option:selected').text();



            $('#txtCode').val(countryCode);

            $('#txtName').val(countryName);

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>



        <asp:DropDownList ID="ddlCountry" runat="server" Width="145px" ClientIDMode="Static">

            <asp:ListItem Value="AF">Afghanistan</asp:ListItem>

            <asp:ListItem Value="AL">Albania</asp:ListItem>

            <asp:ListItem Value="DZ">Algeria</asp:ListItem>

            <asp:ListItem Value="AS">American Samoa</asp:ListItem>

            <asp:ListItem Value="AD">Andorra</asp:ListItem>

            <asp:ListItem Value="AO">Angola</asp:ListItem>

            <asp:ListItem Value="AI">Anguilla</asp:ListItem>

            <asp:ListItem Value="PK">Pakistan</asp:ListItem>

        </asp:DropDownList>

        <input id="txtCode" type="text" />

        <input id="txtName" type="text" />

        <input id="btn" type="button" value="OK" onclick="btnClick()" />

    </div>

    </form>

</body>

</html>

LINQ to SQL using JavaScriptSerilizor

For serilization of code in linq to sql might review this code which resolve your error if occurs

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetEmployee(int employeeId)
{
string returnString = "";
DbTransaction getTransaction = null;
DatabaseDataContext dataContext = null;

try
{
dataContext = new DatabaseDataContext(Classes.Constants.GetConnectionString());
dataContext.Connection.Open();
getTransaction = dataContext.Connection.BeginTransaction();
dataContext.Transaction = getTransaction;

ArrayList ar = new ArrayList();

List getEmployee = dataContext.spEmpSelect(Convert.ToInt64(employeeId)).Select(
p =>
new Employee()
{
A= p.A,
B = p.B,
FirstName = p.FirstName,
LastName = p.LastName

}).ToList();

List getEmAddr= dataContext.sp_getEmAddr(employeeId).Select(
p =>
new EmployeesAddress()
{
Addr = p.Addr,
Address1 = p.Address1,
City = p.City,
Country = p.Country,
ContactNumber1 = p.ContactNumber1,
ContactNumber2 = p.ContactNumber2
}).ToList();


var jss = new JavaScriptSerializer();
ar.Add(getEmployee);
ar.Add(getEmAddr);
returnString = jss.Serialize(ar);
getTransaction.Commit();
}
catch (Exception exception)
{
returnString = exception.Message;
getTransaction.Rollback();
}
finally
{
if (dataContext.Connection.State == System.Data.ConnectionState.Open)
{
dataContext.Connection.Close();
}
}
return returnString;
}

Ajax Modalpopup Extendar

Here is code below to show how to display ajax modalpopup extendar in your web page.

HTML Code

<asp:Button ID="btnShow" runat="server" Text="Show" CausesValidation="false" CssClass="defaultButton"
OnClick="btnShow_Click" />
<asp:HiddenField ID="ShowErrorAlert" runat="server" />
<asp:HiddenField ID="HideErrorAlert" runat="server" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="HideErrorAlert"
TargetControlID="ShowErrorAlert" BackgroundCssClass="popupBackground" PopupControlID="pnlShowErrorAlert" />

<asp:Panel ID="pnlShowErrorAlert" runat="server" Style="display: none;">
<div class="title">
Error Window
</div>
<div class="popupWindow">
<asp:Label ID="lblErrorInfo" runat="server"></asp:Label><br />
<br />
</div>
</asp:Panel>
Button Click Code

protected void btnShow_Click(object sender, EventArgs e)
{
ModalPopupExtender1.Show();
}

Using jQuery to Consume ASP.NET JSON Web Services

jQuery is nowadays a very effective for client side programming as it reduce code and increase the performance of any thing. Calling web service in asp.net using jQuery is very easy as you find a lot of codes on net some of them are so easy and some of them quite complex for the beginners.

First of all here you need to know the output format of web service to pass data to database or retrieve from database. Web Service returns output into two format.
  • XML
  • JSON
Its depend on you which format you like in your coding.

Check this code

Here's the final code which works fine on VS 2008/2010

--------------------------
ASPX MARKUP :
-------------------------------


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonCall.aspx.cs"
      Inherits="Test_Web.JsonCall" %>

<!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 runat="server">
    <title>JSON Call</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

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

        $(function() {

            $("#btnShow").click(function() {

                $.ajax(
                {
                    type: "POST",
                    url: "JsonService.asmx/GetNameById",
                    data: "{'Id':'" + $("#txtID").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data, status) {
                        $("#txtName").val(data.d);
                    },
                    error: function(mgs) {
                        alert(mgs.d);
                    }
                });
            });
        });
     
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="txtID" type="text" /><br />
        <input id="txtName" type="text" /><br />
        <input id="btnShow" type="button" value="Show" />
    </div>
    </form>
</body>
</html>

--------------------------
WEB SERVICE
--------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace Test_Web
{
    /// <summary>
    /// Summary description for JsonService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class JsonService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetNameById(int Id)
        {
            string returnString = "";

            if (Id == 1)
            {
                returnString = "Alpha";
            }
            else if (Id > 1 && Id <= 10)
            {
                returnString = "Beta";
            }
            else
            {
                returnString = "Gamma";
            }

            return returnString;
        }
    }
}

Web services are great tools that afford you substantial flexibility. It’s important not to overlook them. I believe that to be a short-sighted and counterproductive way to do things.

Using jQuery DateTime Picker to select date and time

There are so many JavaScript / jQuery plugins available for showing both date and time in one picker. Its is quiet easy rather than you add two images one for date and other for time. JavaScript date time picker is easily available on Here

First of all I am going to tell you how to integrate this into your webpage. Below example would help you to do so.

------------------------
Process Life Cycle :
-----------------------------

Select time according to need then click on specified date then complete DateTime will show in TextBox then save this value to database using SQL database type "DateTime"

-----------------------
Code Integration :
-----------------------

Then i modified code according to need Here's the HMTL code.


  1. Download JavaScript file and add it to Head tag of page (Get javascript file from below website Javascript name: My Date Time Picker | Creator: TengYong Ng  | Website: http://www.rainforestnet.com)
  2. Then add these lines into body tag

<div>


        <asp:TextBox ID="txtDate" runat="server" Width="150px" MaxLength="25"></asp:TextBox>
        <a href="javascript: NewCssCal('ctl00_HomeContent_Wizard1_txtDate','mmmddyyyy','arrow',true,12,false)">
            <img src="../../Images/cal.gif" width="16" height="16" alt="Pick a date"></a>
</div>

Convert type string to string[ ]

Many peoples asked about the errors that might be occur while conversion in strings. Error is
Cannot implicitly convert type 'string' to 'string[]'

There is very big difference between Convert.ToString() and string[]

Convert.ToString = It converts your array of string into single string instance

For the following code use this

string[] getRoleType = (string[])Session["Role"];