WebAPI: Cascading Dropdown & MVC 4 Entity Framework Scaffolding and Migrations with Seed


Step 1:


Step 2:


Step 3:

Step 4:


Step 5:


Step 6:



Step 7:


Step 8:



Step 9:




Step 10:


Step 11:



Step 12:


Step 13:


Step 14:


Step 15:


Step 16:


Step 17:


Step 18:



Step 19:




Step 20:


Step 21:

Service1.svc

using System.Collections.Generic;
using System.Linq;
using WcfService.Basic.BasicDataContext;

namespace WcfService.Basic
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        private readonly DataContext.BasicDataContext _dataContext = new DataContext.BasicDataContext();

        public IList<Person> GetPersonDetails()
        {
            return _dataContext.Person.ToList();
        }


        public bool GetSuccessLogins(Login login)
        {
            var loginSuccess = _dataContext.Login.FirstOrDefault(l => l.UserName == login.UserName && l.Password == login.Password);
            return loginSuccess != null;
        }


        public bool Register(Login login)
        {
            var registerSuccess = _dataContext.Login.Add(new Login { UserName = login.UserName, Password = login.Password });
            _dataContext.SaveChanges();
            return registerSuccess != null;
        }


        public IList<Country> GetCountry()
        {
            return _dataContext.Country.ToList();
        }


        public IList<State> GetState(string countryCode)
        {
            var stateListItems = _dataContext.State.Where(s => s.CountryCode == countryCode).ToList();
            var stateList = stateListItems.Select(stateListItem => new State {StateId = stateListItem.StateId, StateCode = stateListItem.StateCode, StateName = stateListItem.StateName, CountryCode = stateListItem.CountryCode, Country = stateListItem.Country}).ToList();
            return stateList;
        }

        public IList<City> GetCity(string stateCode)
        {
            var cityListItems = _dataContext.City.Where(c => c.StateCode == stateCode).ToList();
            var cityList= cityListItems.Select(cityListItem => new City {CityId = cityListItem.CityId, CityCode = cityListItem.CityCode, CityName = cityListItem.CityName, StateCode = cityListItem.StateCode, State = cityListItem.State}).ToList();
            return cityList;
        }
    }
}


Step 22:  Set as "Startup project" into WcfService.Basic project before u choosed Packaged Manger Console.


Step 23:


Step 24:


Step 25:


Step 26:



Step 27:


Step 28:


Step 29:

Configuration.cs

using System.Collections.Generic;
using WcfService.Basic.BasicDataContext;

namespace WcfService.Basic.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<WcfService.Basic.DataContext.BasicDataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(WcfService.Basic.DataContext.BasicDataContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            var logins = new List<Login>
                {
                    new Login{UserName = "Arunachala",Password = "Annamalai"},
                    new Login{UserName = "Test",Password = "Test123"}
                };

            logins.ForEach(l => context.Login.AddOrUpdate(lo => lo.UserId, l));
            context.SaveChanges();

            var person = new List<Person>
                {
                    new Person{PersonName = "Venakdesh",PersonCountry = "India",PersonState = "TamilNadu",PersonCity = "Coimbatore"}
                };
            person.ForEach(p=>context.Person.AddOrUpdate(ps=>ps.PersonId,p));
            context.SaveChanges();

            var country = new List<Country>
                {
                    new Country{CountryCode = "IN",CountryName = "India"},
                    new Country{CountryCode = "UK",CountryName = "United Kingdom"}
                };
            country.ForEach(c => context.Country.AddOrUpdate(ctry => ctry.CountryId, c));
            context.SaveChanges();

            var state = new List<State>
                {
                    new State{StateCode = "TN",StateName = "TamilNadu",CountryCode = "IN"},
                    new State{StateCode = "KE",StateName = "Kerala",CountryCode = "IN"},
                    new State{StateCode = "LV",StateName = "LiverPool",CountryCode = "UK"},
                    new State{StateCode = "MU",StateName = "Manchester",CountryCode = "UK"}
                };
            state.ForEach(s => context.State.AddOrUpdate(st => st.StateId, s));
            context.SaveChanges();

            var city = new List<City>
                {
                    new City{CityCode = "CH",CityName = "Chennai",StateCode = "TN"},
                    new City{CityCode = "CBE",CityName = "Coimbatore",StateCode = "TN"},
                    new City{CityCode = "TVM",CityName = "Trivandrum",StateCode = "KE"},
                    new City{CityCode = "TR",CityName = "Trisur",StateCode = "KE"},
                    new City{CityCode = "TC1",CityName = "TestCityOne",StateCode = "LV"},
                    new City{CityCode = "TC2",CityName = "TestCityTwo",StateCode = "LV"},
                    new City{CityCode = "TC3",CityName = "TestCityThree",StateCode = "MU"},
                    new City{CityCode = "TC4",CityName = "TestCityFour",StateCode = "MU"}
                };

            city.ForEach(c => context.City.AddOrUpdate(ct => ct.CityId, c));
            context.SaveChanges();

        }
    }
}

Step 30:

201311140626217_WcfService.Basic.cs

namespace WcfService.Basic.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class WcfServiceBasic : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.UserProfile",
                c => new
                    {
                        UserId = c.Int(nullable: false, identity: true),
                        UserName = c.String(),
                        Password = c.String(),
                    })
                .PrimaryKey(t => t.UserId);
            
            CreateTable(
                "dbo.Person",
                c => new
                    {
                        PersonId = c.Int(nullable: false, identity: true),
                        PersonName = c.String(),
                        PersonCountry = c.String(),
                        PersonState = c.String(),
                        PersonCity = c.String(),
                    })
                .PrimaryKey(t => t.PersonId);
            
            CreateTable(
                "dbo.Employee",
                c => new
                    {
                        EmployeeId = c.Int(nullable: false, identity: true),
                        EmployeeName = c.String(),
                        EmployeeDesignation = c.String(),
                        UserId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.EmployeeId)
                .ForeignKey("dbo.Person", t => t.UserId, cascadeDelete: true)
                .Index(t => t.UserId);
            
            CreateTable(
                "dbo.Country",
                c => new
                    {
                        CountryCode = c.String(nullable: false, maxLength: 3),
                        CountryId = c.Int(nullable: false, identity: true),
                        CountryName = c.String(),
                    })
                .PrimaryKey(t => t.CountryCode);
            
            CreateTable(
                "dbo.State",
                c => new
                    {
                        StateCode = c.String(nullable: false, maxLength: 3),
                        StateId = c.Int(nullable: false, identity: true),
                        StateName = c.String(),
                        CountryCode = c.String(maxLength: 3),
                    })
                .PrimaryKey(t => t.StateCode)
                .ForeignKey("dbo.Country", t => t.CountryCode)
                .Index(t => t.CountryCode);
            
            CreateTable(
                "dbo.City",
                c => new
                    {
                        CityCode = c.String(nullable: false, maxLength: 3),
                        CityId = c.Int(nullable: false, identity: true),
                        CityName = c.String(),
                        StateCode = c.String(maxLength: 3),
                    })
                .PrimaryKey(t => t.CityCode)
                .ForeignKey("dbo.State", t => t.StateCode)
                .Index(t => t.StateCode);
            
        }
        
        public override void Down()
        {
            DropIndex("dbo.City", new[] { "StateCode" });
            DropIndex("dbo.State", new[] { "CountryCode" });
            DropIndex("dbo.Employee", new[] { "UserId" });
            DropForeignKey("dbo.City", "StateCode", "dbo.State");
            DropForeignKey("dbo.State", "CountryCode", "dbo.Country");
            DropForeignKey("dbo.Employee", "UserId", "dbo.Person");
            DropTable("dbo.City");
            DropTable("dbo.State");
            DropTable("dbo.Country");
            DropTable("dbo.Employee");
            DropTable("dbo.Person");
            DropTable("dbo.UserProfile");
        }
    }
}

Step 31.0:




Step 31:


Step 32:


Step 33:


Step 34:


Step 35:


Step 36:


Step 37:


Step 38:



Step 39:


Step 40:


Step 41:

HomePageController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BasicMvcApplication.Controllers
{
    public class HomePageController : Controller
    {
        //
        // GET: /HomePage/

        private readonly BasicWcfService.Service1Client _basicWcfService1Client = new BasicWcfService.Service1Client();

        public ActionResult Login()
        {
            _basicWcfService1Client.GetPersonDetails();
            return View("~/views/BasicViews/LoginPage.cshtml");
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel loginViewModel)
        {
            var login = new BasicWcfService.Login
                {
                    UserName = loginViewModel.UserName,
                    Password = loginViewModel.Password
                };

            var result = _basicWcfService1Client.GetSuccessLogins(login);
            if (result)
            {
                var countryList = _basicWcfService1Client.GetCountry();
                
                var countryItems = countryList.Select(country => new SelectListItem {Text = country.CountryName, Value = country.CountryCode}).ToList();

                var homeViewModel = new HomeViewModel { LoggedUserName = login.UserName,PersonCountry = countryItems,PersonState = new List<SelectListItem>(),PersonCity = new List<SelectListItem>()};

                return View("~/views/BasicViews/HomeView.cshtml", homeViewModel);
            }

            return RedirectToAction("Login");
        }

        public ActionResult Register()
        {
            return View("~/views/BasicViews/RegisterView.cshtml");
        }

        [HttpPost]
        public ActionResult Register(LoginViewModel loginViewModel)
        {
            var login = new BasicWcfService.Login
                {
                    UserName = loginViewModel.UserName,
                    Password = loginViewModel.Password
                };
            var registerResult = _basicWcfService1Client.Register(login);
            if (registerResult)
                return View("~/views/BasicViews/HomeView.cshtml");
            return View("~/views/BasicViews/LoginPage.cshtml");
        }

    }
}

Step 42:

HomeViewModel.cs


using System;

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

namespace BasicMvcApplication.Controllers
{
    public class HomeViewModel
    {
        public int PersonId { get; set; }
        public string LoggedUserName { get; set; }
        public string PersonName { get; set; }
        public string PersonCountryCode { get; set; }
        [Display(Name = "Person Country")]
        public IEnumerable<SelectListItem> PersonCountry { get; set; }
        public string PersonStateCode { get; set; }
        [Display(Name = "Person State")]
        public IEnumerable<SelectListItem> PersonState { get; set; }
        public string PersonCityCode { get; set; }
        [Display(Name = "Person City")]
        public IEnumerable<SelectListItem> PersonCity { get; set; }
        
    }
}

Step 43:

LoginViewModel.cs

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

namespace BasicMvcApplication.Controllers
{
    public class LoginViewModel
    {
        public int UserId { get; set; }
        [Display(Name = "User Name")]
        public string UserName { get; set; }
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
}

Step 44:

BasicViews=>HomeView.cshtml

@using System.Web.Mvc.Html

@model BasicMvcApplication.Controllers.HomeViewModel

@{
    ViewBag.Title = "HomeView";
}

<h2>HomeView</h2>
@using (Html.BeginForm(FormMethod.Post))
{
    @Html.Label("Current User Name:")
    @Html.DisplayFor(m => m.LoggedUserName)<br />

    @Html.LabelFor(m => m.PersonCountry)
    @Html.DropDownListFor(m => m.PersonCountryCode, Model.PersonCountry, "--Select--", new { @id = "ddlCountry" })<br />

    @Html.LabelFor(m => m.PersonState)
    @Html.DropDownListFor(m => m.PersonStateCode, Model.PersonState, "--Select--", new { @id = "ddlState" })<br />

    @Html.LabelFor(m => m.PersonCity)
    @Html.DropDownListFor(m => m.PersonCityCode, Model.PersonCity, "--Select--", new { @id = "ddlCity" })
}



<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/ui.ajax.js"></script>
<script src="~/Scripts/ui.ajaxNavigate.js"></script>
<script src="~/Scripts/ui.js"></script>


<script type="text/javascript">
    $(document).ready(function () {
        $('#ddlCountry').change(function () {
            var countryCode = $("#ddlCountry").val();
            
            $.get("/api/FillState/StateForPersonCountry", { countryCode: countryCode }, function (data) {
                var listItems = "";
                var jsonData = data;
                for (var i = 0; i < jsonData.length; i++) {
                    listItems += "<option value='" + jsonData[i].Value + "' selected='" + jsonData[i].Selected + "'>" + jsonData[i].Text + "</option>";
                }
                $('#ddlState').html(listItems);
            });

           // var uRl = "@Url.Action("StateForPersonCountry", "TestHomePage")'" + "/" + countryCode;
            

        });
        

        $('#ddlState').change(function () {
            var stateCode = $("#ddlState").val();

            $.get("/api/FillState/CityForPersonState", { stateCode: stateCode }, function (data) {
                alert('Test');
                var listItems = "";
                var jsonData = data;
                for (var i = 0; i < jsonData.length; i++) {
                    listItems += "<option value='" + jsonData[i].Value + "' selected='" + jsonData[i].Selected + "'>" + jsonData[i].Text + "</option>";
                }
                $('#ddlCity').html(listItems);
            });

         });

    });
</script>

Step 45:

LoginPage.cshtml

@model BasicMvcApplication.Controllers.LoginViewModel

@{
    ViewBag.Title = "HomeView";
}

<h2>HomeView</h2>

@using (Html.BeginForm())
{
    <fieldset>
        <legend>Log in Form</legend>
        <ol>
            <li>
                @Html.HiddenFor(m=>m.UserId)
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            
        </ol>
        <input type="submit" value="Log in" />
    </fieldset>
<p>
    @Html.ActionLink("Register", "Register","HomePage") if you don't have an account.
</p>
}

Step 46:

Register.cshtml

@model BasicMvcApplication.Controllers.LoginViewModel

@{
    ViewBag.Title = "RegisterView";
}

<h2>RegisterView</h2>

@using (Html.BeginForm()) {   

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            
        </ol>
        <input type="submit" value="Register" />
    </fieldset>
}

Step 47:




Step 48:

FillStateController.cs

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Http;
using System.Web.Mvc;
using BasicMvcApplication.BasicWcfService;

namespace BasicMvcApplication.ApiControllers
{
    public class FillStateController : ApiController
    {
        //
        // GET: /FillState/
        private readonly Service1Client _service1Client=new Service1Client();
        

        [System.Web.Http.HttpGet]
        public ICollection<SelectListItem> StateForPersonCountry(string countryCode)
        {
            var selectList = new Collection<SelectListItem>();
            var stateList = _service1Client.GetState(countryCode);
            foreach (var state in stateList)
            {
                selectList.Add(new SelectListItem{Text = state.StateName,Value = state.StateCode});
            }
            
            return selectList;
        }

        [System.Web.Http.HttpGet]
        public ICollection<SelectListItem> CityForPersonState(string stateCode)
        {
            var selectList = new Collection<SelectListItem>();
            var cityList = _service1Client.GetCity(stateCode);
            foreach (var city in cityList)
            {
                selectList.Add(new SelectListItem { Text = city.CityName, Value = city.CityCode });
            }

            return selectList;
        }

    }
}

Step 49:


Step 50:

RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace BasicMvcApplication
{
    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 = "Home", action = "Index", id = UrlParameter.Optional }
            //);

            routes.MapRoute(
                name: "HomePage",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "HomePage", action = "Login", id = UrlParameter.Optional }
            );

           
        }
    }
}

Step 51:
WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace BasicMvcApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
} 



OutPuts: 









Comments