Introduction
The following is a snapshot of what we will create in this article.
Agenda
- Creating MVC basic application
- Adding an ADO.Net entity model to the application
- Adding a Home Controller
- Adding a View Model (CustomerView)
- Adding a View
- Binding a dropdown to Country
- Binding a dropdown to states based on the country using JSON
- Creating a partial view for displaying records in the Grid
- Final output
I like to write stuff as simple as possible to make them simple to understand for the readers. I have wrote various MVC articles as in the following:
- Creating Insert Update and Delete application In MVC 4 Using Razor
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-insert-update-and-delete-application-in-mvc-4-using/
- Creating Simple WebGrid In MVC 4 Using Simple Model And Dataset
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-webgrid-in-mvc-4-using-simple-model-and-data/
- Binding Dropdownlist With Database In MVC
http://www.c-sharpcorner.com/UploadFile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/
- Creating Simple Cascading Dropdownlist In MVC 4 Using Razor
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/
- Binding Radiobutton and Radiobuttonlist in Various Way in MVC With Database
http://www.c-sharpcorner.com/UploadFile/4d9083/binding-radiobutton-and-radiobuttonlist-in-various-way-in-mv201/
- How to Create Google Charts With MVC 4
http://www.c-sharpcorner.com/UploadFile/4d9083/how-to-create-google-charts-with-mvc-4/
- Globalization and Localization in ASP.Net MVC 4
http://www.c-sharpcorner.com/UploadFile/4d9083/globalization-and-localization-in-Asp-Net-mvc-4/
- Creating Simple Checkbox list in MVC 4 Using Razor
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-checkboxlist-in-mvc-4-using-razor/ Let's start.
- Creating MVC basic application
For creating the basic application in MVC in Visual Studio IDE select "File" -> "New" -> "Project...". A New Project dialog will pop up. Inside that there is a template list and from that select web and in the project template list select
ASP.NET MVC 4 Web Application and name your project
Simplesearch and click on the OK button.
During the adding of the project a new dialog will pop up for selecting the Project Template and inside that select the basic Template.
After creating the application here is the complete folder view.
Now that we have created the application, let's work with the database part.
- Adding an ADO.NET Entity Data Model to the application (.edmx)
In this demo I will use the following 3 tables:
- Country
- State
- Customerdetails
Country Table
State TableCustomerdetails TableProcedure to Add Entity Data ModelWe will add an ADO.NET Entity Data Model in the Model folder.
- For adding, right-click on the Model Folder select Add then inside that select ADO.NET Entity Data Model.
- After selecting, a small dialog will pop up to prompt for a name; I am providing the name OrderDB. Then click on the OK button.
- After clicking on the OK button a new wizard will pop up with the name Entity Data Model wizard. In that select Generate from Database.
- Next a wizard will pop up for the Connection Properties. Here just enter all the connection related information for the database that you want to use and then select “Yes include the sensitive data in the connection string”.
- Now in the next wizard it will ask for selecting tables from the database and inside that select [Country, State , Customerdetails ] then finally click on the Finish button.
After adding the Entity Data Model here is the complete folder view.
For adding the Controller just right-click on the Controller folder select Add then select Controller. After selecting, a new dialog will pop up with the name Add controller. Here we will name the controller HomeController and in the scaffolding option in the template select Empty MVC controller.
The Add Controller dialog snapshot is below:
After adding the Controller the default Index ActionResult is generated, here is the code.
- using System;
- using System.Collections.Generic;
- using System.Data.Objects.SqlClient;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Simplesearch.Models;
-
- namespace Simplesearch.Controllers
- {
- public class HomeController : Controller
- {
-
- [HttpGet]
- public ActionResult Index()
- {
- return View();
- }
-
- }
- }
Now let's move forward and add ViewModel with name CustomerView.
- Adding view Model (CustomerView)
For adding just right-click on the Model folder then select Add then select Class. A new wizard will pop up asking of a class name. Name it CustomerView.cs and click on the Add button.
An empty class is generated.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Simplesearch.Models;
-
- namespace Simplesearch.Models
- {
- public class CustomerView
- {
-
- }
- }
Now let's add some properties to it.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using Simplesearch.Models;
-
- namespace Simplesearch.Models
- {
- public class CustomerView
- {
- public int SelectedCountriesId { get; set; }
- public List<Country> Countrieslist { get; set; }
- public List<Customerdetail> Customerdetail { get; set; }
- }
- }
I have added SelectedCountriesId and Country List properties for binding to the dropdownlist. And for binding the grid I have use a Customerdetail List. And for binding the state we will use JSON. Now we have completed the adding of the View Model, let's add a View.
To add a view just right-click inside the Index ActionResult. A new dialog will pop up with the name Add View and we have a default view name the same as the ActionResult Name (Index). We will not be using the scaffolding template when adding the View.
A blank view is generated and now here is the default code that is generated.
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
Now let's configure an Index [HttpGet] ActionResult such that we can pass a CustomerView Model to the index View. Here is the code that I wrote in the Index ActionResult for binding the Country Dropdownlist. I created an object of OrderDBEntities and using LINQ I get data from the Countries table. And creating the CustomerView object for sending the model to the view and in the Countrieslist property of CustomerView I passed a list, Countrieslist, that we got data for by querying the database.
Code snippet of Index ActionResult
- [HttpGet]
- public ActionResult Index()
- {
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var Countrieslist = (from clist in objord.Countries
- select clist);
-
- CustomerView CV = new CustomerView();
-
- CV.Countrieslist = Countrieslist.ToList();
-
- ViewData["Selectedstate"] = 0;
-
- CV.Customerdetail = null;
-
- return View(CV);
- }
- }
Here you will also find that we have sent a Customerdetail model a null because we are not showing records on the HttpGet request. And using ViewData["Selectedstate"] for maintaining the state after a postback to the controller. For binding the state we will use jQuery ajax and that is why we created a JsonResult to get the state value by passing the country id to Jsonresult.
Code snippet of GetStates JsonResult
- public JsonResult GetStates(string id)
- {
- if (id == null)
- {
- id = "0";
- }
-
- int CountriesID = Convert.ToInt32(id);
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var states = (from slist in objord.States
- where (slist.CountriesID == CountriesID)
- select new { slist.StateID, slist.Statename }).ToList();
-
- return Json(new SelectList(states, "StateID", "Statename"));
- }
After adding an Action method let's move toward configuring a View. We will now add a ViewModel (CustomerView) and a Dropdownlist to the View.
Adding Model to View
- @model Simplesearch.Models.CustomerView
-
- @{
- Layout = null;
- }
Adding a Dropdownlist of County and State to the View.
- <div class="CSSTableGenerator">
- <table style="width: 100%">
- <tr>
- <td>
- @Html.DropDownListFor(m => m.SelectedCountriesId,
- new SelectList(Model.Countrieslist, "CountriesID", "CountriesName"),
- "Select Country", new { style = "width:250px", @class = "dropdown1" })
- </td>
- <td>
- @Html.DropDownList("State",
- new SelectList(string.Empty, "StateID", "Statename"), "Select State",
- new { style = "width:250px", @class = "dropdown1" })
- </td>
-
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="Search" />
- </td>
- </tr>
- </table>
- </div>
After adding a Dropdownlist list, now let's add a jQuery script for binding the state on a change of the country dropdownlist.
- Binding dropdown states based on country using JSON
Adding jQuery Ajax script for binding State dropdownlist.
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
-
- <script type="text/javascript">
- $(document).ready(function () {
-
- $("#SelectedCountriesId").change(function () {
- $("#State").empty();
- $.ajax({
- type: 'POST',
- url: '@Url.Action("GetStates")',
- dataType: 'json',
- data: { id: $("#SelectedCountriesId").val() },
- success: function (states) {
-
-
-
- $("#State").append('<option value="' + "0" + '">' + "Select State" + '</option>');
- debugger;
- $.each(states, function (i, state) {
- $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
-
- });
- },
- error: function (ex) {
- alert('Failed to retrieve states.' + ex);
- }
- });
- return false;
- })
- });
-
- </script>
After adding Dropdownlist and jQuery ajax script now let's run the application and check how your dropdownlist displays.
Here is the View of Index.cshtml after rendering on the browser.
URL: http://localhost:1381/Home/index
We have a dropdownlist bound. Now let's add a partial view.
- Creating Partial view for displaying records in grid
For adding the View just right-click inside Index ActionResult then a new dialog will pop up with the name Add View and we have a default view name the same as the ActionResult name (Index). Just change the name of the view to Displaygrid then we just need to check the “Create as a Partial View” option and click on the Add button.
An empty Partial view is created.
Now let's add a Model to it to display records depending on the Sorting of the dropdownlist. We will use a Customerdetail Model here for displaying the records in Partial view.
- @model List<Simplesearch.Models.Customerdetail>
-
- <link href="~/Content/TableCSSCode1.css" rel="stylesheet" />
- <div class="CSSTableGenerator">
-
- <table>
- <tr>
- <td>Customer ID</td>
- <td>Customer name</td>
- <td>Customer Address</td>
- </tr>
-
- @for (int i = 0; i < Model.Count(); i++)
- {
- <tr>
- <td>
- @Model[i].CustomerID
- </td>
- <td>
- @Model[i].Customername
- </td>
- <td>
- @Model[i].CustomerAddress
- </td>
- </tr>
-
- }
- </table>
-
- </div>
Here I have used a for loop for displaying the list of customers that are sorted depending on dropdownlist. Now we have added the partial view, now let's render the partial view on the Mainpage (Index) and pass the Model to it .
Rendering Partial view on Index page and Passing Model.
- <table style="width: 100%">
- <tr>
- <td>
- @if (Model.Customerdetail != null)
- {
- @Html.Partial("Displaygrid", Model.Customerdetail);
- }
- </td>
- </tr>
- </table>
Finally we will get input from the Index.cshtml View. The [HttpPost] Action Selectors Method that we will create will get a FormCollection and CustomerView as input and in this method we will get a Dropdownlist selected value and from that value we will display the grid.
[HttpPost]
- [HttpPost]
- public ActionResult Index(FormCollection fc, CustomerView objcv)
- {
-
- string CountriesID = Convert.ToString(objcv.SelectedCountriesId);
-
- string StateID = fc["State"];
-
- ViewData["Selectedstate"] = StateID;
-
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var Countrieslist = (from clist in objord.Countries select clist);
-
- CustomerView CV = new CustomerView();
-
-
- int stateid = Convert.ToInt32(StateID);
-
-
- var Customerlist = (from Custlist in objord.Customerdetails
- where Custlist.StateID == stateid
- select Custlist);
-
-
- CV.Countrieslist = Countrieslist.ToList();
-
- CV.SelectedCountriesId = objcv.SelectedCountriesId;
-
- CV.Customerdetail = Customerlist.ToList();
-
- return View(CV);
- }
Here we are getting the posted value of the Country and State dropdownlist.
- string CountriesID = Convert.ToString(objcv.SelectedCountriesId);
- string StateID = fc["State"];
Here I have used a ViewData to show the selected state after posting to the controller. We lose the state of the dropdownlist after posting.
- ViewData["Selectedstate"] = StateID;
Here we are rebinding a Country dropdownlist to maintain the state after posting to the controller.
- OrderDBEntities objord = new OrderDBEntities();
- var Countrieslist = (from clist in objord.Countries select clist);
Here we are getting data from the database according to the state dropdownlist. Finally assigning all the values to the CustomerView to send it to the View.
- CustomerView CV = new CustomerView();
-
-
- int stateid = Convert.ToInt32(StateID);
-
-
- var Customerlist = (from Custlist in objord.Customerdetails
- where Custlist.StateID == stateid
- select Custlist);
-
- CV.Countrieslist = Countrieslist.ToList();
-
- CV.SelectedCountriesId = objcv.SelectedCountriesId;
-
- CV.Customerdetail = Customerlist.ToList();
-
- return View(CV);
Finally to maintain (the state dropdownlist) state I have called a rebindState() function on the Windows.onload method that will check whether or not ViewData["Selectedstate"] is “0” and depending on it it will bind the State dropdownlist and then it will make the state dropdownlist selected.
- if (@ViewData["Selectedstate"] != 0)
- {
- $("#State").val(@ViewData["Selectedstate"]);
- }
Here is the complete code of the snippet of rebindState().
- <script type="text/javascript">
- window.onload = function()
- {
- rebindState ()
- };
- </script>
-
-
- <script type="text/javascript">
-
- function rebindState () {
- debugger;
- if (@ViewData["Selectedstate"] != 0) {
- $("#SelectedCountriesId").val(@Model.SelectedCountriesId);
-
- $.ajax({
- type: 'POST',
- url: '@Url.Action("GetStates")',
- dataType: 'json',
- data: {
- id: $("#SelectedCountriesId").val()
- },
- success: function (states) {
-
- $.each(states, function (i, state) {
- $("#State").append('<option value="' + state.Value + '">'
- + state.Text + '</option>');
-
- if (@ViewData["Selectedstate"] != 0) {
- $("#State").val(@ViewData["Selectedstate"]);
- }
-
- });
- },
- error: function (ex) {
- alert('Failed to retrieve states.' + ex);
- }
- });
- }
-
-
- }
- </script>
Completed Home Controller Code snippet
- using System;
- using System.Collections.Generic;
- using System.Data.Objects.SqlClient;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Simplesearch.Models;
-
- namespace Simplesearch.Controllers
- {
- public class HomeController : Controller
- {
-
- [HttpGet]
- public ActionResult Index()
- {
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var Countrieslist = (from clist in objord.Countries
- select clist);
-
- CustomerView CV = new CustomerView();
-
- CV.Countrieslist = Countrieslist.ToList();
-
- ViewData["Selectedstate"] = 0;
- CV.Customerdetail = null;
- return View(CV);
- }
-
-
-
- [HttpPost]
- public ActionResult Index(FormCollection fc, CustomerView objcv)
- {
-
- string CountriesID = Convert.ToString(objcv.SelectedCountriesId);
- string StateID = fc["State"];
- ViewData["Selectedstate"] = StateID;
-
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var Countrieslist = (from clist in objord.Countries select clist);
-
- CustomerView CV = new CustomerView();
-
-
- int stateid = Convert.ToInt32(StateID);
-
-
- var Customerlist = (from Custlist in objord.Customerdetails
- where Custlist.StateID == stateid
- select Custlist);
-
-
- CV.Countrieslist = Countrieslist.ToList();
-
- CV.SelectedCountriesId = objcv.SelectedCountriesId;
-
- CV.Customerdetail = Customerlist.ToList();
-
- return View(CV);
- }
-
-
-
-
- public JsonResult GetStates(string id)
- {
- if (id == null)
- {
- id = "0";
- }
-
-
- int CountriesID = Convert.ToInt32(id);
-
-
- OrderDBEntities objord = new OrderDBEntities();
-
- var states = (from slist in objord.States
- where (slist.CountriesID == CountriesID)
- select new { slist.StateID, slist.Statename }).ToList();
-
- return Json(new SelectList(states, "StateID", "Statename"));
- }
- }
- }
Completed Index.cshtml Code snippet
- @model Simplesearch.Models.CustomerView
-
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
-
-
- <link href="~/Content/TableCSSCode(1).css" rel="stylesheet" />
- <link href="~/Content/TableCSSCode.css" rel="stylesheet" />
-
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
-
- <script type="text/javascript">
- $(document).ready(function () {
-
- $("#SelectedCountriesId").change(function () {
- $("#State").empty();
- $.ajax({
- type: 'POST',
- url: '@Url.Action("GetStates")',
- dataType: 'json',
- data: { id: $("#SelectedCountriesId").val() },
- success: function (states) {
-
-
-
- $("#State").append('<option value="' + "0" + '">' + "Select State" + '</option>');
- debugger;
- $.each(states, function (i, state) {
- $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
-
- });
- },
- error: function (ex) {
- alert('Failed to retrieve states.' + ex);
- }
- });
- return false;
- })
- });
-
- </script>
- <script type="text/javascript">
- window.onload = function () { rebindState() };
- </script>
-
-
- <script type="text/javascript">
-
- function rebindState() {
- debugger;
- if (@ViewData["Selectedstate"] != 0) {
- $("#SelectedCountriesId").val(@Model.SelectedCountriesId);
-
- $.ajax({
- type: 'POST',
- url: '@Url.Action("GetStates")',
- dataType: 'json',
- data: {
- id: $("#SelectedCountriesId").val()
- },
- success: function (states) {
-
- $.each(states, function (i, state) {
- $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
-
- if (@ViewData["Selectedstate"] != 0) {
- $("#State").val(@ViewData["Selectedstate"]);
- }
-
- });
- },
- error: function (ex) {
- alert('Failed to retrieve states.' + ex);
- }
- });
- }
-
-
- }
- </script>
-
- </head>
- <body>
- @using (Html.BeginForm())
- {
- @Html.ValidationSummary(true)
- <div class="CSSTableGenerator">
- <table style="width: 100%">
- <tr>
- <td>
- @Html.DropDownListFor(m => m.SelectedCountriesId,
- new SelectList(Model.Countrieslist, "CountriesID", "CountriesName"), "Select Country", new { style = "width:250px", @class = "dropdown1" })
- </td>
- <td>
- @Html.DropDownList("State",
- new SelectList(string.Empty, "StateID", "Statename"), "Select State", new { style = "width:250px", @class = "dropdown1" })
- </td>
-
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="Search" />
- </td>
- </tr>
- </table>
- </div>
- <table style="width: 100%">
- <tr>
- <td>
- @if (Model.Customerdetail != null)
- {
- @Html.Partial("Displaygrid", Model.Customerdetail);
- }
- </td>
- </tr>
- </table>
-
- }
- </body>
- </html>
Completed Displaygrid.cshtml Code snippet
- @model List<Simplesearch.Models.Customerdetail>
-
- <link href="~/Content/TableCSSCode1.css" rel="stylesheet" />
- <div class="CSSTableGenerator">
-
- <table>
- <tr>
- <td>Customer ID</td>
- <td>Customer name</td>
- <td>Customer Address</td>
- </tr>
-
- @for (int i = 0; i < Model.Count(); i++)
- {
- <tr>
- <td>
- @Model[i].CustomerID
- </td>
- <td>
- @Model[i].Customername
- </td>
- <td>
- @Model[i].CustomerAddress
- </td>
- </tr>
-
- }
-
-
- </table>
- </div>
Final OutputHere I have selected the country India and the state Maharashtra and clicked on the Search button then it brought all the customer-related data of Maharashtra into the grid.
If I select the country India and the state Rajasthan and click on the Search button then it shows all the customer-related information of Rajasthan in the grid.