Sunday 27 December 2015

How to register with cascading drop down in mvc4

Hello Friends,
                                Now I am going to describe  how to create a Register form with Cascading Dropdown list and Login form using  MVC4 in C#. Follow the steps.
Step-1
First create a website File->New->Project->select Web from left side-> ASP.NET MVC 4 Web Application->Provide Name(Suppose mvcregistration_dropdown)->click on ->OK->Than Select a template->Internet Application->OK.

Step-2
create four tables,three tables(country,state,city) for dropdown bind and anather table(suppose- userinfo) for save like this: 
country :

state
 
city
 
userinfo

Step-3
create a Store Procedure ( "insertpro") like this:
 ALTER Procedure insertpro
(
@iflag varchar(50),
@name varchar(50)=null,
@emailid varchar(50)=null,
@Password varchar(50)=null,
@country varchar(50)=null,
@state varchar(50)=null,
@city varchar(50)=null
)
AS
begin
SET NOCOUNT ON
if(@iflag='insert')
begin
      Insert Into userinfo(name,emailid,Password,country,state,city) values(@name,@emailid,@Password,@country, @state, @city)
end
if(@iflag='signin')
begin
Select emailid,password from userinfo where emailid=@emailid and password =@Password

end
END

Step-4
select your database from serverexplore and go to properties and copy your connection string,than add it in web.config file within connectionstring tag. like this:

<connectionStrings>
<add name="myentities" connectionString="Data Source=.\;Initial Catalog=mymvcdb;Integrated Security=True" providerName="System.Data.SqlClient" /> 
</connectionStrings>

Step-5

Create 3 models for country,state,city like this:
countrymodel:-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
    [Table("Country")]
    public class CountryModel
    {
        [Key]
        public int CountryId { get; set; }
        public string Country { get; set; }
    }
}
Step-6
statemodel:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
    [Table("State")]
    public class StateModel
    {
        [Key]
        public int Id { get; set; }
        public int CountryId { get; set; }
        public string State { get; set; }
    }
}
Step-7
citymodel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
    [Table("City")]
    public class CityModel
    {
        [Key]
        public int Id { get; set; }
        public int StateId { get; set; }
        public string City { get; set; }
    }
}
 Step-8
  
for add Dbcontext create anather model  "myentities"

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
    public class
myentities: DbContext
    {
       
        public DbSet<CountryModel> Countries { get; set; }
        public DbSet<StateModel> States { get; set; }
        public DbSet<CityModel> Cities { get; set; }
        public DbSet<register> reg { get; set; }
      
       
    }
}

Step-9
 create anather two model for login and register:

loginmodel:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
    public class loginmodel
    {
        SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["
myentities"].ConnectionString);
        [Required(ErrorMessage = "emailid is mandatory")]
        [Display(Name = "emailid")]
        public string emailid { get; set; }

        [Required(ErrorMessage = "password is mandatory")]
        [Display(Name = "password")]
        public string password { get; set; }




        public bool login_info(string emailid, string password)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("insertpro", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@iflag", "signin");
                cmd.Parameters.AddWithValue("@emailid", emailid);
                cmd.Parameters.AddWithValue("@password", password);
                Object obj = cmd.ExecuteScalar();
                if (obj == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                GC.Collect();

            }
        }
    }
}
Step-10
 model for Register name is-"register"
 using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;


namespace mvcregistration_dropdown.Models
{
 
    public class register
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["
myentities"].ConnectionString);
        [Key] //Primary Key
        public int Id { get; set; }
        [Required(ErrorMessage = "Name is mandatory")]
        [Display(Name = "Ename")]
        public string Ename { get; set; }

        [Required(ErrorMessage = "emailid is mandatory")]
        [Display(Name = "emailid")]
        public string emailid { get; set; }

        [Required(ErrorMessage = "password is mandatory")]
        [Display(Name = "password")]
        public string password { get; set; }

        [Required(ErrorMessage = "Country is mandatory")]
        [Display(Name = "Country")]
        public string Country { get; set; }

        [Required(ErrorMessage = "State is mandatory")]
        [Display(Name = "State")]
        public string State { get; set; }

        [Required(ErrorMessage = "City is mandatory")]
        [Display(Name = "City")]
        public string City { get; set; }



        public bool InsertRecord(register reg)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("insertpro", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@iflag", "insert");
                cmd.Parameters.Add("@name", System.Data.SqlDbType.VarChar, 50).Value = reg.Ename;
                cmd.Parameters.Add("@emailid", System.Data.SqlDbType.VarChar, 50).Value = reg.emailid;
                cmd.Parameters.Add("@password", System.Data.SqlDbType.VarChar, 50).Value = reg.password;
                cmd.Parameters.Add("@Country", System.Data.SqlDbType.VarChar, 50).Value = reg.Country;
                cmd.Parameters.Add("@State", System.Data.SqlDbType.VarChar, 50).Value = reg.State;
                cmd.Parameters.Add("@City", System.Data.SqlDbType.VarChar, 50).Value = reg.City;
                Object obj = cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                GC.Collect();
              
            }
        }

      
    }
    }
 Step-11
double click on "HomeController"  write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using mvcregistration_dropdown.Models;


namespace mvcregistration_dropdown.Controllers
{
    public class HomeController : Controller
    {
        CountryEntities db = new CountryEntities();

        [HttpGet]
        public ActionResult homepage()
        {
            ViewData["Message"] = "";
            return View();
        }

        [HttpGet]
        public ActionResult welcome()
        {
           ViewData["Message"] = "";
            return View();
        }
        [HttpGet]
        public ActionResult Index()
        {
           ViewData["Message"] = "";
            return View();
        }

        [HttpPost]
        public ActionResult Index(register regd)
        {

            if (ModelState.IsValid)
            {
                regd.InsertRecord(regd);
                ViewData["Message"] = "Your Record inserted sucessfully..";
                return View();
            }
            else
            {
                ViewData["Message"] = "";
                return View();
            }
        }
         [HttpGet]
        public ActionResult Login()
        {
            ViewData["Message"] = "";
            return View();

        }


         [HttpPost]
         public ActionResult Login(loginmodel objsignin)
         {
             if (ModelState.IsValid)
             {
                 if (objsignin.login_info(objsignin.emailid, objsignin.password))
                 {
                     return View("welcome");
                  }
                 else
                 {
                     ViewBag.Message = "Invalid Username or password";
                     return View();
                 }
             }
             else
             {
                 return View();
             }
         }
        public JsonResult GetCountries()
        {
            return Json(db.Countries.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetStatesByCountryId(string countryId)
        {
            int Id = Convert.ToInt32(countryId);
            var states = from a in db.States where a.CountryId == Id select a;
            return Json(states);
        }

        public JsonResult GetCitiesByStateId(string stateId)
        {
            int Id = Convert.ToInt32(stateId);
            var cities = from a in db.Cities where a.StateId == Id select a;
            return Json(cities);
        }
    }
}
 
 Step-12
Goto HomeController  double click over homepage and right click->addview like this:
View for homepage:

homepage.cshtml

@model mvcregistration_dropdown.Models.register

@{
    ViewBag.Title = "homepage";
}

<h2>welcome to our home page...</h2>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
   </head>
<body>
    <div>
            <input id="btnsignin" type="button" value="Sign In" onclick="@("window.location.href='" + @Url.Action("Login", "Home") + "'");" />
            <input id="btnsignup" type="button" value="Sign Up" onclick="@("window.location.href='" + @Url.Action("Index", "Home") + "'");" />
    </div>
</body>
</html>
 Step-13
View for Register:
Index.cshtml
@model mvcregistration_dropdown.Models.register

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
     <script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    $(function () {
        $.ajax({
            type: "GET",
            url: "/home/GetCountries",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.Country + '</option>');
                });
            }
        });

        $('#dropdownCountry').change(function () {

            $('#dropdownState').empty();

            $.ajax({
                type: "POST",
                url: "/home/GetStatesByCountryId",
                datatype: "Json",
                data: { countryId: $('#dropdownCountry').val() },
                success: function (data) {
                    $.each(data, function (index, value) {
                        $('#dropdownState').append('<option value="' + value.Id + '">' + value.State + '</option>');
                    });
                }
            });
        });

        $('#dropdownState').change(function () {

            $('#dropdownCity').empty();

            $.ajax({
                type: "POST",
                url: "/home/GetCitiesByStateId",
                datatype: "Json",
                data: { stateId: $('#dropdownState').val() },
                success: function (data) {
                    $.each(data, function (index, value) {
                        $('#dropdownCity').append('<option value="' + value.Id + '">' + value.City + '</option>');
                    });
                }

            });
        });

    });
</script>
</head>
<body>

    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "FormName" }))
    {
        <div><input id="btnlogin" type="button" value="Login" onclick="@("window.location.href='" + @Url.Action("Login", "Home") + "'");" /></div>
        <fieldset style="width: 400px;">
                 <div>
                
                 <legend>Sign up page</legend>
                  <div>
                    @ViewData["Message"]
                </div>
                 <label>Registration : </label>
                </div>
                <div style="width: 100px; float: left;">
                    @Html.LabelFor(m => m.Ename)
                </div>
                <div>
                    @Html.TextBoxFor(m => m.Ename, new { id = "txtName" })
                    @Html.ValidationMessageFor(m => m.Ename)
                </div>
               <div style="width: 100px; float: left;">
                    @Html.LabelFor(m => m.emailid)
                </div>
                <div>
                    @Html.TextBoxFor(m => m.emailid, new { id = "txtemailid" })
                    @Html.ValidationMessageFor(m => m.emailid)
                </div>
               <div style="width: 100px; float: left;">
                    @Html.LabelFor(m => m.password)
                </div>
                <div>
                    @Html.PasswordFor(m => m.password, new { id = "txtpassword" })
                    @Html.ValidationMessageFor(m => m.password)
                </div>
                <div style="width: 100px; float: left;">
            <label>Country : </label>
        </div>
        <div style="width: 200px; float: left;">

         @Html.DropDownListFor(m => m.Country, new SelectList(string.Empty, "Value", "Text"), "Please select country", new { id = "dropdownCountry" })

            @*Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select country", new { @style = "width:200px;" })*@
        </div>
    <div style="width: 100%;float:left;margin-top:35px;">
        <div style="width: 100px; float: left;">
            <label>State : </label>
        </div>
        <div style="width: 200px; float: left;">
        @Html.DropDownListFor(m => m.State, new SelectList(string.Empty, "Value", "Text"), "Please select State", new { id = "dropdownState" })
           @* @Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select state", new { @style = "width:200px;" })*@
        </div>
    </div>
    <div style="width: 100%;float:left;margin-top:35px;">
        <div style="width: 100px; float: left;">
            <label>City : </label>
        </div>
        <div style="width: 200px; float: left;">
        @Html.DropDownListFor(m => m.City, new SelectList(string.Empty, "Value", "Text"), "Please select country", new { id = "dropdownCity" })
            @*@Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select city", new { @style = "width:200px;" })*@
        </div>
        </div>
    <div>
          <input type="submit" value="Submit" onclick="" />
        </div>
        </fieldset>
    }
</body>
   
</html>
 
Step-14
View for Login
Login.cshtml
@model mvcregistration_dropdown.Models.loginmodel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>login</title>
</head>
 <body>
    <div >
        @using (Html.BeginForm("Login", "Home", FormMethod.Post))
        {
           
            <fieldset style="max-width:500px;">
                <legend> Login Form</legend>
              
                <div>
                    <div>
                        emailid
                    </div>
                    <div>
                        @Html.TextBoxFor(m => m.emailid)
                        @Html.ValidationMessageFor(m => m.emailid)
                    </div>
                </div>
                <div>
                    <div>
                        password
                    </div>
                    <div>
                        @Html.PasswordFor(m => m.password)
                        @Html.ValidationMessageFor(m => m.password)
                        @ViewBag.Message
                    </div>
                </div>
                <div>
                    <input type="submit" title="Submit" />
                </div>
            </fieldset>
        }
    </div>
</body>
</html>
Step-15
After login it go to anather page i.e.(suppose "welcome") 

welcome.cshtml

@model mvcregistration_dropdown.Models.register

@{
    ViewBag.Title = "welcome";
}

<h2>welcome</h2>
<p>Hellow world................</p>


I have explained Register with cascading drop downlist,login system of asp.net in c# using store procedure with mvc4 application.
So after read please Comments and suggestions.
Thanks & Regard
Rabi


No comments:

Post a Comment