-->

How to create Feedback page with cascade dropdownlist in MVC4.





Introduction

This is the 4th part of this series, where I am going to explain how to create feedback page with cascade dropdown list in MVC4.

Sometimes you need to display dropdown lists in your ASP.NET MVC views such that values in one dropdown list are dependent on the value selected in another dropdown list. The most common example of such a functionality is countries and states dropdown lists, where based on a selected country you need to populate the state's dropdown list. In this article I would like to explain how to create feedback page with cascade dropdown list in MVC4.

I have explained following articles in the series "Implement basic functionality in asp.net MVC application"
  1. How to create a User Registration page using asp.net mvc
  2. How to create a login page using asp.net mvc
  3. How to create career page with Upload file (CV) in MVC
  4. How to create Feedback page with cascade dropdownlist in MVC.
  5. How to display database data in webgrid in mvc

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for Save data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Feedback Table

Country Table


State Table



Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Apply validation on model.

Open your model and add validation. Please follow below code

namespace MVCFeedbackWithCasecadeDD
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    public partial class Feedback
    {
        public int FeedbackID { get; set; }
        [Display(Name="Full Name")]
        [Required(ErrorMessage="Please provide your fullname", AllowEmptyStrings = false)]
        public string FullName { get; set; }
        [Display(Name="Mobile No")]
        public string MobileNo { get; set; }
        [Display(Name="Country")]
        [Required(ErrorMessage="Please select country", AllowEmptyStrings=false)]
        public int CountryID { get; set; }
        [Display(Name="State")]
        [Required(ErrorMessage="Please select state", AllowEmptyStrings=false)]
        public int StateID { get; set; }
    }
}

Step-6: Create a Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "FeedbackController"

Step-7: Add new action into your controller for Get Method

Here I have added "Submit" Action into "Feedback" Controller. Please write this following code

namespace MVCFeedbackWithCasecadeDD.Controllers
{
    public class FeedbackController : Controller
    {
        //
        // GET: /Feedback/

        public ActionResult Submit()
        {
            List<Country> allCountry = new List<Country>();
            List<State> allState = new List<State>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
            ViewBag.CountryID = new SelectList(allCountry, "CountryID", "CountryName");
            ViewBag.StateID = new SelectList(allState, "StateID", "StateName");
            return View();
        }
    }
}

Step-8: Add view for your Action & design for create form.

Right Click on Action Method (here right click on Submit action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
HTML and Jquery Code
@model MVCFeedbackWithCasecadeDD.Feedback
@{
    ViewBag.Title = "Submit";
}
<h2>Submit</h2>

@using (Html.BeginForm("Submit","Feedback", FormMethod.Post)) {
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Feedback</legend>
        @if (ViewBag.Message != null)
        {
            <div style="border:solid 1px black">
                @ViewBag.Message
            </div>
        }
        <div class="editor-label">
            @Html.LabelFor(model => model.FullName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FullName)
            @Html.ValidationMessageFor(model => model.FullName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.MobileNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.MobileNo)
            @Html.ValidationMessageFor(model => model.MobileNo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CountryID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.CountryID,@ViewBag.CountryID as SelectList,"Select Country")
            @Html.ValidationMessageFor(model => model.CountryID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StateID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.StateID,@ViewBag.StateID as SelectList, "Select State")
            @Html.ValidationMessageFor(model => model.StateID)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script language="javascript">
        $(document).ready(function () {
            $("#CountryID").change(function () {
                // this will call when Country Dropdown select change
                var countryID = parseInt($("#CountryID").val());
                if (!isNaN(countryID)) {
                    var ddState = $("#StateID");
                    ddState.empty(); // this line is for clear all items from State dropdown
                    ddState.append($("<option></option").val("").html("Select State"));

                    // Here I will call Controller Action via Jquery to load State for selected Country
                    $.ajax({
                        url: "@Url.Action("GetStates","Feedback")",
                        type: "GET",
                        data: { countryID: countryID },
                        dataType: "json",
                        success: function (data) {
                            $.each(data, function (i, val) {
                                ddState.append(
                                        $("<option></option>").val(val.StateID).html(val.StateName)
                                    );
                            });
                        },
                        error: function () {
                            alert("Error!");
                        }
                    });
                }
            });
        });
    </script>
}

Step-9: Add new action into your controller for POST Method

Here I have added "Submit" Action with Model Parameter (here "Feedback") into "Feedback" Controller. Please write this following code

[HttpPost]
[ValidateAntiForgeryToken] // this is for prevent CSRF Attack
public ActionResult Submit(Feedback fb)
{
    List<Country> allCountry = new List<Country>();
    List<State> allState = new List<State>();

    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
        if (fb != null && fb.CountryID > 0)
        {
            allState = dc.States.Where(a => a.CountryID.Equals(fb.CountryID)).OrderBy(a => a.StateName).ToList();
        }
    }

    ViewBag.CountryID = new SelectList(allCountry, "CountryID", "CountryName",fb.CountryID);
    ViewBag.StateID = new SelectList(allState, "StateID", "StateName",fb.StateID);
            

    if (ModelState.IsValid)
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            dc.Feedbacks.Add(fb);
            dc.SaveChanges();
            ModelState.Clear();
            fb = null;
            ViewBag.Message = "Successfully submitted"; 
        }
    }
    else
    {
        ViewBag.Message = "Failed! Please try again";
    }
    return View(fb);
}

Step-10: Add new action into your controller for Get Method for Get Data for Cascade Dropdownlist

Here I have added "GetStates" Action into "Feedback" Controller. Please write this following code

[HttpGet]
public JsonResult GetStates(string countryID = "")
{
    List<State> allState = new List<State>();
    int ID = 0;
    if (int.TryParse(countryID,out ID))
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            allState = dc.States.Where(a => a.CountryID.Equals(ID)).OrderBy(a => a.StateName).ToList();
        }
    }
    if (Request.IsAjaxRequest())
    {
        return new JsonResult
        {
            Data = allState,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
    else
    {
        return new JsonResult
        {
            Data = "Not valid request",
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

Step-12: Run Application.







Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.