Click here to Skip to main content
Click here to Skip to main content

Using Controls are Dropdownlist, RadioButtonList, DateTime Calender, FileUpload, Cascading Dropdown

, 24 Nov 2013
Rate this:
Please Sign up or sign in to vote.
How to use different controls in MVC application
Sample Image - maximum width is 600 pixels


This article aims to discuss the different controls in MVC. Those who are new to MVC can learn about how to use Textbox, Dropdownlist, RadioButtonList, DateTime Calender, Cascading dropdownlist, Checkbox, Checkboxlist, Listbox, FileUpload, Image and Modalpopup in MVC application. Many people are getting confused using controls after a long time use of ASP.NET controls. That's why this article will explain to you with some simple steps to use these controls in MVC application. There are many approaches to use controls but I have gone through some simple steps to use it. Hope that it will help you.


MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the model is represented by the actual content. It comes in different flavors. The HTML is the "skeleton" of bedrock content. The CSS adds visual style to the content. It is the "skin" that we use to flesh out our skeleton and give it a particular look. We can swap in different skins via CSS without altering the original content in any way. They are relatively, but not completely, independent.

Design Model

See this person class designed to act for different controls. Where FullName purpose of textbox, Gender -> RadioButtonList, DateOfBirth -> DateTimeCalender, IsMarried -> Checkbox, Country, State, City are for cascading dropdownlist, Photo -> FileUpload and Image, Interest -> ListBox. And finally CountryV, StateV and CityV presents the foreign key relationships in entity model and purpose to view show names to their ids.

DropDownList Control

The DropDownList control is used to create a drop-down list. Each selectable item in a DropDownList control is defined by a SelectListItem element!

            @Html.DropDownList("FullName", new List<SelectListItem>{
            new SelectListItem{Text="Mr.",Value="Mr."},
            new SelectListItem{Text="Mrs.",Value="Mrs."}

Represents the drop down list with its options: SelectListItem. This class has three properties:

  • string Text – The string that will be displayed as text of the option
  • string Value – The string that will be used as the value of the option
  • bool Selected – Whether the option is selected (one more option)

RadioButtonList Control

The RadioButton method is designed to make it easy to bind to view data or model data.

            @Html.RadioButton("Gender", "Male")Male
            @Html.RadioButton("Gender", "Female")Female      

In the above cases, both RadioButtons names are same with "Gender" represents as RadioButtonList. If this radio button is selected, the value of the radio button is submitted when the form is posted.

DateTime Calender Control

Before you start using DateTime Calender, make sure that Scripts/jquery-ui-... is available or not. Or you can install from Manage Nuget Packages for Solution. See one image below:

After this install is successful, edit your _Layout.cshtml page from Shared folder. Comment your previous used Scripts reference @* @Scripts.Render("~/bundles/jquery")*@ and add reference inside header tag.

After this setting, we will go to create page to view Dropdownlist calender. For this, I have simply written in Create.cshtml for textbox design @Html.TextBox("DateOfBirth") and for Calender, just call inside script is that $('#DateOfBirth').datepicker();.

Cascading dropdownlist Control

Here, I will explain with three dropdowns Country, State, City dropdown I need to populate states dropdown based on country dropdown and I need to populate city dropdown based on states dropdown for that what we have to do is first design three class in model with data like this:

First, I have gone through Country DropDownList. This load has made it two types in jquery and MVC pattern in this solution when you can find out after download, Alright I have commented jquery side due to purpose of different implementation where I am implementing Country as MVC pattern and State, City as jquery pattern. So that you can clear both sides. First, I have collected country list as ViewBag Dynamic object, then feed it in design side.

       Controllers -> ActionResult Create() 
         //Get list of Countries to load on dropdownlist
            ViewBag.Country = new SelectList(db.Countries.ToList(), "ID", "CountryName", "ID");
        Views -> Create.cshtml
          @Html.DropDownList("Country", ViewBag.Country as SelectList, 
          "Select Country", new { style = "width:200px" })    

See in the above code ViewBag.Country taking list from controls to View. After this state populate based on Country selection, sending country id to controls ActionResultMethod. This is implemented in jquery where actionresult will return Json type list. See the code below:

   Controllers ->  
       public JsonResult GetStates(int id)
            var states = db.States.Where(x => x.CountryID == id).ToList();
            return Json(states, JsonRequestBehavior.AllowGet);
  Views -> Jquery
           $("#Country").change(function () {
            var url = "/Controls_/GetStates";
            var countryID = $("#Country").val();
            $.post(url, { id: countryID }, function (data) {
                $("#State").empty();   $("#City").empty();             
                var items = "<option>Select State<option>";
                $.each(data, function (i, states) {
                    items += "<option value=" + states.ID + ">" + states.StateName + "</option>";

State is loaded on change event of country dropdownlist. It's same for city dropdownlist will populate on State dropdown selection. See the following codes:

 Controllers ->  
        public JsonResult GetCities(int id)
            var city = db.Cities.Where(x => x.StateID == id).ToList();
            return Json(city, JsonRequestBehavior.AllowGet);
 Views -> Jquery
        //Load City on select of State
        $("#State").change(function () {
            var url = "/Controls_/GetCities";
            var stateID = $("#State").val();
            $.post(url, { id: stateID }, function (data) {
                var items = "<option>Select City</option>";
                $.each(data, function (i, City) {
                    items += "<option value=" + City.ID + ">" + City.CityName + "</option>";


CheckBox Control

This control is so simple to present in design View. Where I have mentioned a Field IsMarried in Model of Person class.

At the time of Add View Scafold Template type is creating checkbox for a boolean type object.


Checkboxlist Control

It's way to use MVC Checkboxlist at the install of "Install-Package MvcCheckBoxList" this. You can get the details here. But for now to show one simple way to do this. First, create a list of string and take with ViewBag to our design page. See the codes below:

      Controllers -> public ActionResult Create() 

         //Make list for Hobbies
            ViewBag.Hobbies = new List<string /> { "Reading", "Singing", "Dancing", "Joking", "Cricket" };

     Views -> Design

         @foreach (var item in ViewBag.Hobbies as List<string />)
                <input type="checkbox" name="Hobbies" value="@item"> @item

In the above code, put list values inside an HTML input tag. Here all input names are the same for the purpose of checkboxlist. And ViewBag.Hobies are converted to List<string> and @item is putting values. It will represent as below:

Listbox Control

Html.ListBoxFor format; the first parameter sets the property of the model to use (one of the arrays); the second parameter creates a MultiSelectList, which is a collection of objects similar to the ListItem class in Web Forms - each item has a value, text, and selected property. The constructor sets the collection to use as the list, and the properties to use as the value and text fields, as well as an IEnumerable representing the values that should be selected to which we pass one of our arrays. Because it's a MultiSelectList, multiple items can be selected and moved at the same time.

    Controllers -> public ActionResult Create() 
         //Make list of Interest
            ViewBag.Interest = new List<SelectListItem> { 
                new SelectListItem{Text="Pop-music",Value="Pop-music"},
                new SelectListItem{Text="Cinema",Value="Cinema"},
                new SelectListItem{Text="Swimming",Value="Swimming"},
                new SelectListItem{Text="Game",Value="Game"},
                new SelectListItem{Text="Cooking",Value="Cooking"}
Views -> Design
     @Html.ListBox("Interest", ViewBag.Interest as IEnumerable
     	<SelectListItem>, new { style = "width:200px;" })    

FileUpload Control

Using plain HTML input file type tag.

           <input name="Photo" id="Photo" type="file" />    

Image Control

Again I am using HTML tag to display image. See byte[] saved for database and image to display from a byte array. Where folder path will simple for everyone and this is also. But for demo purposes, I am going through varbinary format. When I come to display the details for a Person, I get stuck on displaying the Image. I did the following method:

  Controllers -> public  FileContentResult getImg(int id) 
        public FileContentResult getImg(int id)
            byte[] byteArray = db.Persons.Find(id).Photo;
            if (byteArray != null)
                return new FileContentResult(byteArray, "image/jpeg");
                return null;
 Views -> Design
         <img  src="@Url.Action("getImg", "Controls_", new { id = Model.ID })" alt="Person Image"/>    

ModalPopup Control

For this, I have taken the help of JqueryUi scripts. I am showing Country, State, City as a modal popup to add data now for demo. What I have done exactly is added a common jquery method to script and call Calling Controls ActionResult method here.

    Controllers -> public  ActionResult _Country( ) 
        public ActionResult _Country()
            return View();

 Views -> Design
          @Html.ActionLink("+Add Country", 
          "_Country", "Controls_", null,
            new { @class = "openDialog", 
               data_dialog_id = "aboutlDialog", 
               data_dialog_title = "Country" })

Views -> Jquery
   $.ajaxSetup({ cache: false }); 
    $(document).ready(function () {
        $(".openDialog").click(function (e) {

                .attr("id", $(this)
                    title: $(this).attr("data-dialog-title"),
                    close: function () { $(this).remove(); },
                    modal: true,
                    height: 250,
                    width: 500,
                    left: 0

        $(".close").click(function (e) {


After using different controls, it's sending input data to ActionResult Create() method.

  Controllers -> public  FileContentResult Create 
        public ActionResult Create(FormCollection collection)
                Person person = new Person();
                person.FullName = collection["FullName"].Replace(",", " ");
                person.Gender = collection["Gender"];
                person.DateOfBirth = Convert.ToDateTime(collection["DateOfBirth"]);
                person.IsMarried = Convert.ToBoolean(collection["IsMarried"].Split(',')[0]);
                person.SpouseName = collection["SpouseName"];
                person.Country = Convert.ToInt32(collection["Country"]);
                person.State = Convert.ToInt32(collection["State"]);
                person.City = Convert.ToInt32(collection["City"]);
                person.Photo = imageToByteArray(collection["Photo"]);
                person.Interest = collection["Interest"];
                person.Hobbies = collection["Hobbies"];
                //FOREIGN KEY constraint value set to Person Entities
                person.CountryV = db.Countries.Find(person.Country);
                person.StateV = db.States.Find(person.State);
                person.CityV = db.Cities.Find(person.City);
                //End of key settings
                return RedirectToAction("Index");
                return View();

Here, FormCollection class object sends all input types of object to HttpPost Create method. For Person FullName object FormCollection object is sending Dropdownlist with Textbox value as(Dropdownlist SelectedValue, Textbox Text) due to the same name. Same as Checkbox list inputs are sending selected values with comma separated "Reading, Singing, Cricket". See in the above, it is assigning StateV as selection of StateID and so on. This will populate as Country name in details or index page.

            @Html.DisplayFor(modelItem => item.CountryV.CountryName)
            @Html.DisplayFor(modelItem => item.StateV.StateName)
            @Html.DisplayFor(modelItem => item.CityV.CityName)


For MVC app, the model is any of the logic or the database or any of the data itself. The view is simply how you lay the data out, how it is displayed. If you want a subset of some data, for example, my opinion is that it is a responsibility of the model. The model knows how to make a subset. You should not be asking your graphics designer to filter a list according to age or some other criteria.

I hope that the article is helpful to developers who are interested in, or working, on MVC applications.


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


About the Author

sankarsan parida
Software Developer
India India
Hi all,I am Sankarsan Parida,I am working as a Software Engineer in CTS Kolkata. I have around 4 years of experience in developing the web applications. My areas of interest are C#.Net, Ajax, Sql server, MongoDB, MVC, WCF
Follow on   Google+

Comments and Discussions

QuestionError when tryng to create new record PinmemberKevin Gaskin30-Jun-14 4:53 
AnswerRe: Error when tryng to create new record Pinprofessionalsankarsan parida30-Jun-14 7:21 
GeneralRe: Error when tryng to create new record PinmemberKevin Gaskin30-Jun-14 7:35 
GeneralRe: Error when tryng to create new record Pinprofessionalsankarsan parida2-Jul-14 3:18 
GeneralRe: Error when tryng to create new record PinmemberKevin Gaskin2-Jul-14 4:19 
GeneralRe: Error when tryng to create new record Pinprofessionalsankarsan parida3-Jul-14 1:05 
QuestionNice PinprofessionalRahul VB6-May-14 23:58 
AnswerRe: Nice Pinprofessionalsankarsan parida7-May-14 0:46 
QuestionTryModelUpdate PinmemberAntonio Ripa6-Jan-14 12:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 24 Nov 2013
Article Copyright 2013 by sankarsan parida
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid