Sunday, August 3, 2014

Parent and Child dependent dropdown list using MVC

My objective is to dependent drop down list.

Output:



















Step1: Please have a look below view code

@model ContosoUniversity.Models.Enrollment

@{
    ViewBag.Title = "Create";
}

<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#Countries").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")', // we are calling json method
                dataType: 'json',
                data: { id: $("#Countries").val() },
               // here we are get value of selected country and passing same value as inputto json method GetStates.
                success: function (states) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(states, function (i, state) {
                    $("#State").append('<option value="' + state.Value + '">' +  state.Text + '</option>');                                                                                                
                    // here we are adding option for States
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });

</script>

<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="'+ city.Value + '">'+ city.Text + '</option>');
                    });
                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });

</script> 

@Scripts.Render("~/bundles/jqueryui")
<script >
    $(function () {
        $("#datepicker").datepicker();
    });
</script>

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    
    
    
    <fieldset>
        <legend>Enrollment</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.CourseID, "Course")
        </div>
        <div class="editor-field">
            @Html.DropDownList("CourseID", String.Empty)
            @Html.ValidationMessageFor(model => model.CourseID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentID, "Student")
        </div>
        <div class="editor-field">
            @Html.DropDownList("StudentID", String.Empty)
            @Html.ValidationMessageFor(model => model.StudentID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Grade)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Grade)
            @Html.ValidationMessageFor(model => model.Grade)
        </div>

        <div>
            @Html.DropDownList("Countries", ViewData["country"] as List<SelectListItem>)
        </div>
        
        <div>
            @Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "d1" })
        </div>

        <div>
            @Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "d1" })
        </div>

        
        
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Step2: have a look controller.


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContosoUniversity.Models;
using ContosoUniversity.DAL;

namespace ContosoUniversity.Controllers
{
    public class EnrollmentController : Controller
    {
        private SchoolContext db = new SchoolContext();

        //
        // GET: /Enrollment/

        public ActionResult Index(int? page)
        {
            var enrollments = db.Enrollments.Include(e => e.Course).Include(e => e.Student);
            return View(enrollments.ToList());
        }

        //
        // GET: /Enrollment/Details/5

        public ActionResult Details(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        //
        // GET: /Enrollment/Create

        public ActionResult Create()
        {
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title");
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName");

            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "Select", Value = "0" });
            li.Add(new SelectListItem { Text = "Bangladesh", Value = "1" });
            li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
            li.Add(new SelectListItem { Text = "China", Value = "3" });
            li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
            li.Add(new SelectListItem { Text = "USA", Value = "5" });
            li.Add(new SelectListItem { Text = "UK", Value = "6" });
            ViewData["country"] = li;


            return View();
        }

        //
        // POST: /Enrollment/Create

        [HttpPost]
        public ActionResult Create(Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Enrollments.Add(enrollment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);



            return View(enrollment);
        }

        //
        // GET: /Enrollment/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        //
        // POST: /Enrollment/Edit/5

        [HttpPost]
        public ActionResult Edit(Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Entry(enrollment).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        //
        // GET: /Enrollment/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        public ActionResult getCourseId(string course)
        {
            return View(course);
        }

        //
        // POST: /Enrollment/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            db.Enrollments.Remove(enrollment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public JsonResult GetStates(string id)
        {
            List<SelectListItem> states = new List<SelectListItem>();
            switch (id)
            {
                case "1":
                    states.Add(new SelectListItem { Text = "Select", Value = "0" });
                    states.Add(new SelectListItem { Text = "Dhaka", Value = "1" });
                    states.Add(new SelectListItem { Text = "Khulna", Value = "2" });
                    states.Add(new SelectListItem { Text = "Borishal", Value = "3" });
                    states.Add(new SelectListItem { Text = "Chittagong", Value = "4" });
                    states.Add(new SelectListItem { Text = "Syllet", Value = "5" });
                    break;
                case "UK":
                    break;
                case "India":
                    break;
            }

            return Json(new SelectList(states, "Value", "Text"));

        }

        public JsonResult GetCity(string id)
        {
            List<SelectListItem> City = new List<SelectListItem>();
            switch (id)
            {
                case "1":
                    City.Add(new SelectListItem { Text = "Select", Value = "0" });
                    City.Add(new SelectListItem { Text = "Gazipur", Value = "1" });
                    City.Add(new SelectListItem { Text = "Gopalgong", Value = "2" });

                    break;
            }
            return Json(new SelectList(City, "Value", "Text"));
        }
    }

}

Step3: then you will get above output

No comments: