Click here to Skip to main content
15,916,280 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Please give me sample code or correct my code if any one have solution for how to make Cascade dropdown list with MVC razor by using entity framework. My code is

Controller:

public ActionResult Index(string MatchTypeName, string CompetitionName, string MatchName, string GroundName, string ReportName)
{
foreach (WebReportType WebRepots in db.WebReportTypes)
{
SelectListItem selectReportType = new SelectListItem
{
Text = WebRepots.ReportName,
Value = WebRepots.ReportName,

};

SelectReports.Add(selectReportType);

ViewBag.ReportName = SelectReports;
}

foreach (MatchTypeMaster MatchType in db.MatchTypeMasters)
{
SelectListItem selectMatchTypes = new SelectListItem
{
Text = MatchType.MatchTypeName,
Value = MatchType.MatchTypeID,

};

selectMatchTypeList.Add(selectMatchTypes);

ViewBag.MatchTypeName = selectMatchTypeList;
}

foreach (Competition CompMatchType in db.Competitions)
{

SelectListItem selectCompetitionTypes = new SelectListItem
{
Text = CompMatchType.CompetitionName,
Value = CompMatchType.CompetitionID,

};

selectCompetitionList.Add(selectCompetitionTypes);
ViewBag.CompetitionName = selectCompetitionList;
}

foreach (Match Match in db.Matches)
{

SelectListItem selectMatch = new SelectListItem
{
Text = Match.MatchName,
Value = Match.MatchID,

};

selectMatchList.Add(selectMatch);
ViewBag.MatchName = selectMatchList;
}

foreach (Ground Ground in db.Grounds)
{

SelectListItem selectGround = new SelectListItem
{
Text = Ground.GroundName,
Value = Ground.GroundID,

};

selectGroundList.Add(selectGround);
ViewBag.GroundName = selectGroundList;
}

View:


@Html.DropDownList("ReportName", ViewData["ReportName"] as MultiSelectList, new { multiple = "multiple", @class = "multiselect" , style = "width: 400px"})

@Html.DropDownList("MatchName", ViewData["MatchName"] as MultiSelectList, new { multiple = "multiple", @class = "multiselect" , style = "width: 400px"})

@Html.DropDownList("MatchTypeName", ViewData["MatchTypeName"] as MultiSelectList, new { multiple = "multiple", @class = "multiselect" })
Posted

1 solution

HTML
i have given my code just try it...

in view folder  Index.cshtml

@{
    ViewBag.Title = "DropDownList Demo";
}

<h5>Cascade DropDownList Demo</h5>

@Html.ValidationSummary("Please correct the errors and try again.")

@using (Html.BeginForm())
{
    <fieldset>
        <legend>DropDownList</legend>
        @Html.Label("Name")
        @Html.TextBox("Name")
        @Html.ValidationMessage("Name", "*")

        @Html.Label("State")
        @Html.DropDownList("State", ViewBag.StateName as SelectList, "Select a State", new { id = "State" })
        @Html.ValidationMessage("State", "*")

        @Html.Label("District")
        <select id="District"  name="District"></select>
        @Html.ValidationMessage("District", "*")

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


@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(function () {
        $('#State').change(function () {
            $.getJSON('/DDL/DistrictList/' + $('#State').val(), function (data) {
                var items = '<option>Select a District</option>';
                $.each(data, function (i, district) {
                    items += "<option value='" + district.Value + "'>" + district.Text + "</option>";
                });
                $('#District').html(items);
            });
        });
    });
</script>




IN Controller DDlController.cs

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

namespace MvcCascadingDropdownlist.Controllers
{
    public class DDLController : Controller
    {
        //
        // GET: /DDL/

        public ActionResult Index()
        {
            List<SelectListItem> state = new List<SelectListItem>();
            state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
            state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
            ViewBag.StateName = new SelectList(state, "Value", "Text");

            return View();
        }

        public JsonResult DistrictList(string Id)
        {
            var district = from s in District.GetDistrict()
                           where s.StateName == Id
                           select s;

            return Json(new SelectList(district.ToArray(), "StateName", "DistrictName"), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Index(ApplicationForm formdata)
        {
            if (formdata.Name == null)
            {
                ModelState.AddModelError("Name", "Name is required field.");
            }
            if (formdata.State == null)
            {
                ModelState.AddModelError("State", "State is required field.");
            }
            if (formdata.District == null)
            {
                ModelState.AddModelError("District", "District is required field.");
            }

            if (!ModelState.IsValid)
            {
                //Populate the list again
                List<SelectListItem> state = new List<SelectListItem>();
                state.Add(new SelectListItem { Text = "Bihar", Value = "Bihar" });
                state.Add(new SelectListItem { Text = "Jharkhand", Value = "Jharkhand" });
                ViewBag.StateName = new SelectList(state, "Value", "Text");

                return View("Index");
            }

            //TODO: Database Insertion
            
            return RedirectToAction("Index", "Home");
        }
    }
}

In Model ApplicationForm.cs

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

namespace MvcCascadingDropdownlist.Models
{
    public class ApplicationForm
    {
        public string Name { get; set; }
        public string State { get; set; }
        public string District { get; set; }
    }

    public class District
    {
        public string StateName { get; set; }
        public string DistrictName { get; set; }

        public static IQueryable<District> GetDistrict()
        {
            return new List<District>
            {
                new District { StateName = "Bihar", DistrictName = "Motihari" },
                new District { StateName = "Bihar", DistrictName = "Muzaffarpur" },
                new District { StateName = "Bihar", DistrictName = "Patna" },
                new District { StateName = "Jharkhand", DistrictName = "Bokaro" },
                new District { StateName = "Jharkhand", DistrictName = "Ranchi" },
            }.AsQueryable();
        }
    }
}
 
Share this answer
 
Comments
Ruter11 7-Sep-13 0:51am    
I will try this one but I want the e.g. in which values are comming from SQL database using Entity Framework

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900