.

Creating a cascade dropdown in MVC & C# (version 2)

Now, let’s follow the steps.
Step 1
At very first, we need a model class that defines properties for storing data.
    public class ApplicationForm
    {
        public string Name { get; set; }
        public string State { get; set; }
        public string District { get; set; }
    }
Step 2
Now, we need an initial controller that will return an Index view by packing list of states in ViewBag.StateName.
    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();
    }
In above controller we have a List<SelectListItem> containing states attached to ViewBag.StateName. We could get list of states form database using Linq query or something and pack it to ViewBag.StateName, well let’s go with in-memory data.
Step 3
Once we have controller we can add its view and start creating a Razor form.
@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>
}
You can see I have added proper labels and validation fields with each input controls (two DropDownList and one TextBox) and also a validation summery at the top. Notice, I have used <select id=”District”….> which is HTML instead of Razor helper this is because when we make JSON call using jQuery will return HTML markup of pre-populated option tag. Now, let’s add jQuery code in the above view page.
Step 4
Here is the jQuery code making JSON call to DDL named controller’s DistrictList method with a parameter (which is selected state name). DistrictList method will returns JSON data. With the returned JSON data we are building <option> tag HTML markup and attaching this HTML markup to ‘District’ which is DOM control.
@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>
Please make sure you are using jQuery library references before the <script> tag.
Step 5
In above jQuery code we are making a JSON call to DDL named controller’s DistrictList method with a parameter. Here is the DistrictList method code which will return JSON data.
    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);
    }
Please note, DistrictList method will accept an ‘Id’ (it should be ‘Id’ always) parameter of string type sent by the jQuery JSON call. Inside the method, I am using ‘Id’ parameter in linq query to get list of matching districts and conceptually, in the list of district data there should be a state field. Also note, in the linq query I am making a method call District.GetDistrict().
Step 6
In above District.GetDistrict() method call, District is a model which has a GetDistrict() method. And I am using GetDistrict() method in linq query, so this method should be of type IQueryable. Here is the model code.
    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();
        }
    }
Step 7
You can run the application here because cascading dropdownlist is ready now. I am going to do some validation works when user clicks the submit button. So, I will add another action result of POST version.
    [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”);
    }

And, this action result will accept ApplicationForm model data and based on posted data will do validations. If a validation error occurs, the action method calls the AddModelError method to add the error to the associated ModelState object. The AddModelError method accepts the name of the associated property and the error message to display. After the action method executes the validation rules, it uses the IsValid property of the ModelStateDictionary collection to determine whether the resulting data complies with the model.

Creating a cascade dropdown in MVC & C# (version 1)

 

public class MyViewModel
{
    public int? Year { get; set; }
    public int? Month { get; set; }

    public IEnumerable<SelectListItem> Years
    {
        get
        {
            return Enumerable.Range(2000, 12).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = x.ToString()
            });
        }
    }
}

 

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    public ActionResult Months(int year)
    {
        if (year == 2011)
        {
            return Json(
                Enumerable.Range(1, 3).Select(x => new { value = x, text = x }), 
                JsonRequestBehavior.AllowGet
            );
        }
        return Json(
            Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
            JsonRequestBehavior.AllowGet
        );
    }
}

 

@model AppName.Models.MyViewModel

@Html.DropDownListFor(
    x => x.Year, 
    new SelectList(Model.Years, "Value", "Text"),
    "-- select year --"
)

@Html.DropDownListFor(
    x => x.Month, 
    Enumerable.Empty<SelectListItem>(),
    "-- select month --"
)

<script type="text/javascript">
    $('#Year').change(function () {
        var selectedYear = $(this).val();
        if (selectedYear != null && selectedYear != '') {
            $.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
                var monthsSelect = $('#Month');
                monthsSelect.empty();
                $.each(months, function (index, month) {
                    monthsSelect.append($('<option/>', {
                        value: month.value,
                        text: month.text
                    }));
                });
            });
        }
    });
</script>

Displaying a datatable

To display a Data Table:

@model System.Data.DataTable
@using System.Data;

<h2>View Table</h2>

<table>
    <thead>
    <tr>
    @foreach (DataColumn col in Model.Columns)    
    {         
        <th>@col.ColumnName</th>
    }    
    </tr>
    </thead>        
    <tbody>
    @foreach (DataRow row in Model.Rows)    
    {        
        <tr>
        @foreach (DataColumn col in Model.Columns)        
        {             
            <td>@row[col.ColumnName]</td>
        }        
        </tr>
    }    
    </tbody>
</table>

You can get data as follows:

public DataTable GetDataForSql(string sql, string connectionString)
{
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        using(SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = sql;
            connection.Open();          
            using(SqlDataReader reader = command.ExecuteReader())
            {
                DataTable data = new DataTable();
                data.Load(reader);
                return data;
            }

        }

    }

}

If you just wanted a DataTable then the following method is short and reduces complexity:

<code>public DataTable GetDataForSql(string sql, string connectionString)
{
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        using(SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = sql;
            connection.Open();          
            using(SqlDataReader reader = command.ExecuteReader())
            {
                DataTable data = new DataTable();
                data.Load(reader);
                return data;
            }

        }

    }

}</code>

usage:

<code>try{
    DataTable results = GetDataForSql("SELECT * FROM Table;", ApplicationSettings["ConnectionString"]);
}
catch(Exception e)
{
    //Logging
    //Alert to user that command failed.
}</code>

working with links

this will perform a “Back” operation:

@Html.ActionLink(“Quick Login”, “Login”, “Account”, null, new { data_icon = “arrow-r”, data_rel = “back” })

MVC Razor – working with combobox/dropdown controls

Rendering a dropdown in MVC with an id and preselected value etc.

Class

public class Ward 
{
    public int Ward_id{get ;set;}
    public string Ward_name{get ;set;}
    public List<Wards> GetAll() 
    {
        //code here
    }
}

 

Controller:

model.Wards = Ward.GetAll();
model.Wards.Insert(0,new Wards() { Ward_name="all", Ward_id = -1});
model.SelecteWardId = id;

View:

 

@Html.DropDownListFor(n => n.Wards, new SelectList(
    Model.Wards,"Ward_id","Ward_name", Model.SelecteWardId),
        new Dictionary<string, object> { { "id", "TheIdForTheDropdown" }
        { //can add click events etc here too 
  } })

this renders:

<select id="TheIdForTheDropdown" name="Wards"><option value="-1">all</option>
<option value="1">A</option>
<option selected="selected" value="2">B</option>
<option value="3">C</option>
</select>