Wednesday, December 9, 2015

Cascading DropDownList In MVC

In this article I am going to explain how to create cascading dropdownlist in MVC.

Step1

In Visual Studio Go to  Menu File->New->Project, and click on Project.



Step2


After Clicking on project the given below window will be open (the output looks like):


select ASP.NET MVC 4 Web Appliaction rename the name value to (CascadingDropDownMVC), then click on OK button

Step3

After completing the step 2 new window will be open the output is looks like


In it select the Basic  project template and click on "OK" button, after clicking on "OK" button your solution explorer look like



Step 4

After the completing step 3 , I add a class in my model (Right click on Model folder at solution explorer) the output will look like(Here click on class menu item)



Now new window will be open,  rename the class name (StateCity.cs)  (output look like) then click on Add Button.


your "StateCity.cs" class has been created.

Step 5

Before writing the code in class firstly create  two tables "city" and "state" in your database ,
you may use the given below script for tables creation.

DataBase Structure of City,State


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[State](
                [StateID] [int] IDENTITY(1,1) NOT NULL,
                [StateName] [varchar](50) NOT NULL,
                [active] [bit] NULL,
                [Latitude] [varchar](35) NULL,
                [Longitude] [varchar](35) NULL,
 CONSTRAINT [PK_StateMaster] PRIMARY KEY CLUSTERED
(
                [StateID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[State] ON
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (3, N'Andaman and Nicobar', 1, N'6deg.  and 14deg.N', N'92deg. and 94deg. E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (4, N'Andhra Pradesh', 1, N'12deg.41min and 22Deg. N', N'77deg.and 84deg.40min E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (5, N'Assam', 1, N'24deg.  3min and 27deg. 58min N', N'89deg.5min and 96deg. 1min E')
SET IDENTITY_INSERT [dbo].[State] OFF
/****** Object:  Table [dbo].[TCity]    Script Date: 12/10/2015 12:34:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TCity](
                [CityID] [int] IDENTITY(1,1) NOT NULL,
                [CityName] [varchar](100) NOT NULL,
                [StateId] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
                [CityID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[TCity] ON
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (2, N'ANDAMAN ISLAND', 3)
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (3, N'NICOBAR ISLAND', 3)
SET IDENTITY_INSERT [dbo].[TCity] OFF
/****** Object:  ForeignKey [fk_StateId]    Script Date: 12/10/2015 12:34:50 ******/
ALTER TABLE [dbo].[TCity]  WITH CHECK ADD  CONSTRAINT [fk_StateId] FOREIGN KEY([StateId])
REFERENCES [dbo].[State] ([StateID])
GO
ALTER TABLE [dbo].[TCity] CHECK CONSTRAINT [fk_StateId]


Now we write the code of  "StateCity.cs" class.

StateCity.cs


using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CascadingDropDownMVC.Models
{
    public class StateCity
    {

      //return connection string

        string Constr = ConfigurationManager.ConnectionStrings["Con"].ToString();
     
        public List<SelectListItem> State = null;
        public int StateID { set; get; }
        public List<SelectListItem> City = null;
        public int CityID { set; get; }

        //return state list
        public List<SelectListItem> GetState()
        {
            SqlDataReader dr = null;
            State = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select StateID,StateName from State", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
           
            State.Add(new SelectListItem { Text = "Select State", Value = "0", Selected = true });
            while (dr.Read())
            {
                State.Add(new SelectListItem { Text = Convert.ToString(dr["StateName"]), Value = Convert.ToString(dr["StateID"]), Selected = true });
            }
            return State;
        }
        //return city list on behalf of state id

        public List<SelectListItem> GetCity(string StateID)
        {
            SqlDataReader dr = null;
            City = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select CityID,CityName from TCity  where StateId=" + StateID + "", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
            City.Add(new SelectListItem { Text = "Select City", Value = "0", Selected = true });
            while (dr.Read())
            {
                City.Add(new SelectListItem { Text = Convert.ToString(dr["CityName"]), Value = Convert.ToString(dr["CityID"]), Selected = true });
            }
            return City;
        }
    }
}

Step 6
Now Right Click on Controller folder at solution explorer add a new Controller (the out put will look like) now click on Controller


 a new window will be open name it to  index. The out put will look like


now click on Add button
Step 8
Write the code in IndexController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropDownMVC.Models;
namespace CascadingDropDownMVC.Controllers
{
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        public ActionResult Index()
        {
            StateCity obj = new StateCity();
            ViewBag.State = obj.GetState();
            return View();
        }
        public JsonResult City(string StateID)
        {
            List<SelectListItem> City = new List<SelectListItem>();
            StateCity obj = new StateCity();
            City = obj.GetCity(StateID);
            return Json(City);
        }
    }
}

Step 9

Create a View for this contoller, now right click on Index ActionResult method , a popup window will be open click on Add View  and write the code given below:

@model CascadingDropDownMVC.Models.StateCity
@{
    ViewBag.Title = "Cascading DropdownList in MVC";
}
<style type="text/css">
  .inpt       { border:1px solid #CCC; background:#ffffff; margin:0 0 5px; padding:5px; color:#444444; }
.inpt:hover { -webkit-transition:border-color 0.3s ease-in-out; -moz-transition:border-color 0.3s ease-in-out; transition:border-color 0.3s ease-in-out; border:1px solid #AAA; }
.inpt:focus { border:1px solid #395b77; outline:none; }
</style>
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(document).ready(function () {
        $("#StateID").change(function () {
            if ($("#StateID").val() != "0") {
                var options = {};
                options.url = "/index/City";
                options.type = "POST";
                options.data = JSON.stringify({ StateID: $("#StateID").val() });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (City) {
                    $("#city").empty();
                    for (var i = 0; i < City.length; i++) {
                        alert(City[i].Value);
                        alert(City[i].Text);
                        $("#city").append('<option value="' + City[i].Value + '">' + City[i].Text + '</option>');
                    }
                    $("#city").prop("disabled", false);
                };
                options.error = function () { alert("Error retrieving city!"); };
                $.ajax(options);
            }
            else {
                $("#city").empty();
                $("#city").prop("disabled", true);
            }
        });
    });
</script>
<h2>Cascading DropdownList in MVC</h2>
<table>
<tr>
<td style="width:50px;"><b>State</b> :</td>
<td>@Html.DropDownListFor(model => model.StateID, new SelectList(ViewBag.State, "Value", "Text"), new { @class = "inpt" })</td>
</tr>
<tr>
<td style="width:50px;"><b>City</b> :</td>
<td>@Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "inpt" })</td>
</tr>
</table>

Now rest of changes we will done in "RouteConfig.cs", At the solution explorer App_Start folder conatin this file

changes in RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CascadingDropDownMVC
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Now Run you application output will look like:

Output:

Tuesday, December 8, 2015

Cascading DropDown List in ASP.NET C#


In this article, I am going to explain how to code for cascading dropdown list in asp.net c#

Step 1

In VS File->New->WebSite->ASP.NET Empty WebSite->OK



Step 2

At the Solution Explorer. Right Click at Solution Explorer->Add New Item




Step 3

After Clicking on New Item. Select Web Service and rename it to "CascadingDropDownList.asmx.cs" and then click ADD Button


Step 5

Add the refrence of Ajax Contol ToolKit at Solution Explorer

Step 6
After Adding the ToolKit , Write code in (DropdownWebService.cs)
using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Configuration;
using System.Data;
/// <summary>
/// Summary description for DropdownWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class DropdownWebService: System.Web.Services.WebService
{
    [WebMethod]
    public CascadingDropDownNameValue[] BindStatedropdown(string knownCategoryValues, string category)
    {
        SqlConnection constate = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);
        constate.Open();
        SqlCommand cmdstate = new SqlCommand("select StateCode, StateName from tbl_StateMaster", constate);
        cmdstate.ExecuteNonQuery();
        SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
        DataSet dsstate = new DataSet();
        dastate.Fill(dsstate);
        constate.Close();
        List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
        statedetails.Add(new CascadingDropDownNameValue("Select State", "0"));
        foreach (DataRow dtstaterow in dsstate.Tables[0].Rows)
        {
            string stateID = dtstaterow["StateCode"].ToString();
            string statename = dtstaterow["StateName"].ToString();
            statedetails.Add(new CascadingDropDownNameValue(statename, stateID));
        }
        return statedetails.ToArray();
    }
    [WebMethod]
    public CascadingDropDownNameValue[] BindRegiondropdown(string knownCategoryValues, string category)
    {
        int stateID;
        StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        stateID = Convert.ToInt32(statedetails["State"]);
        SqlConnection conregion = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);
        conregion.Open();
        SqlCommand cmdregion = new SqlCommand("select CityCode,CityName from tbl_CityMaster where StateCode=@StateID", conregion);
        cmdregion.Parameters.AddWithValue("@StateID", stateID);
        cmdregion.ExecuteNonQuery();
        SqlDataAdapter daregion = new SqlDataAdapter(cmdregion);
        DataSet dsregion = new DataSet();
        daregion.Fill(dsregion);
        conregion.Close();
        List<CascadingDropDownNameValue> regiondetails = new List<CascadingDropDownNameValue>();
        regiondetails.Add(new CascadingDropDownNameValue("select", "0"));
        foreach (DataRow dtregionrow in dsregion.Tables[0].Rows)
        {
            string regionID = dtregionrow["CityCode"].ToString();
            string regionname = dtregionrow["CityName"].ToString();
            regiondetails.Add(new CascadingDropDownNameValue(regionname, regionID));
        }
        return regiondetails.ToArray();
    }
}

Step 7

After writing the code in (DropdownWebService.asmx.cs). Again write click at Solution Explorer ->Add New Item->Web Form->(rename CascadingDropDown.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CascadingDropDown.aspx.cs"
    Inherits="CascadingDropDown" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <table style="width: 100%">
        <tr>
            <td style="width: 100px;">
                State:
            </td>
            <td>
                <asp:DropDownList ID="ddlState" runat="server" CssClass="inpt">
                </asp:DropDownList>
                <asp:CascadingDropDown ID="StateCascading" runat="server" Category="State" TargetControlID="ddlState"
                    LoadingText="Loading States..." ServiceMethod="BindStatedropdown" ServicePath="~/DropdownWebService.asmx">
                </asp:CascadingDropDown>
            </td>
        </tr>
        <tr>
            <td style="width: 100px">
                City
            </td>
            <td>
                <asp:DropDownList ID="ddlCity" runat="server" CssClass="inpt">
                </asp:DropDownList>
                <asp:CascadingDropDown ID="RegionCascading" runat="server" Category="Region" TargetControlID="ddlCity"
                    ParentControlID="ddlState" LoadingText="Loading Cities..." ServiceMethod="BindRegiondropdown"
                    ServicePath="~/DropdownWebService.asmx">
                </asp:CascadingDropDown>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Step 7

After the Writing this Code Press F5 and get the Output

Sunday, June 14, 2015

C# - Indexers

Indexers allow you to use an index on an object to obtain the values stored within the object. The behavior of the indexers is similar to properties; we use get and set methods for define indexers. Properties return a specific data member while indexer returns a particular value from the object.
Properties are defined by the properties name while defining the indexers we use this keyword. Indexers modifier cab be public private, protected or internal. Indexer must have at least one parameter.

Example.   - using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication39
{
   public class Class1
    {
       string[] s = new string[3];
       public string this[int index]
       {
           get
           {
               return s[index];
           }
           set
           {
               s[index] = value;
           }
       }

    }
}


.cs code - 

private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            obj[1] = "Sachin";
           MessageBox.Show(obj[1]).ToString();
          

        }

Output -



                                                                   Author:Sachin Pathak

Properties in C#

In C#, properties are the natural extension of data fields. They are also known as ‘smart field’.
Inside a class, we declare a data field as a private and provide a set of public set and get method to access the data fields, because the data field cannot be accessed directly outside the class so we use get and set methods.

Example:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication38
{
   public class Class1
    {
       
        private int i;
        public int prop
        {
            get
            {
                return i;
            }
       
            set
            {
                i = value;
            }
        }

    }
}

.cs code:
  private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            int x = obj.prop;
            x = 10;
            MessageBox.Show(x.ToString());

        }


Output :