ASP.NET - ASP.NET MVC3 Question-How to populate three "DropDownList"

Asked By A S on 14-Aug-11 10:59 AM
Assume I am developing asp.net mvc3 C# web application; how can I populate three dropdownlists where second dropdownlist depends on what user selects in first dropdownlist and third dropdownlist depends on what user selects in second dropdownlist.

Thank you in advance!d
Radhika roy replied to A S on 14-Aug-11 01:23 PM

There are a few different ways to dynamically populate a dropdownlist in MVC: you could use a classic ASP old school loop with a bunch of response.writes, you can store the list’s collection into ViewData and use an html helper, or you can use jquery. We’ll look at samples for each way.

Populate dropdownlist with response.writes

We will start out with the least elegant solution, but it does work nonetheless. So this is the code inside your view:

1
2
3
4
5
6
7
<select id="ID" name="ID">
  <%
   Contact[] contacts = Contact.FindAll();
   for(int i=0; i < contacts.length;i++){ %>
   <option value="\""">" + contacts[i].FullName + "</option>
   <% } %>
</select>

Populate dropdownlist with ViewData

This method is better, and is baked right into MVC. The downside is you can only use it in MVC, and involves using ViewData (detailed http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx), the View and the Controller. First we prepare the Controller:

1
2
3
4
5
6
public ActionResult Index()
{
  Contact[] contacts = Contact.FindAll();
  ViewData["Contacts"] = new SelectList(contacts,"ID","FullName", <span style="color:red;">[Selectedvalue]</span>);
  return View();
}

Selectedvalue – this optional parameter can be used to select a specific value, useful if you are displaying a form in edit mode.

The last part is binding the ViewData contents to a dropdownlist in the View:

1
<%= Html.DropDownList("Contacts") %>

Populate dropdownlist with jQuery

This is the most flexible of the three, and can be used in web forms, php, MVC, etc. This method involves a jquery call in javascript:

1
2
3
4
5
6
7
8
9
10
<script language="javascript" type="text/javascript">
  $(function() {
    $.getJSON("YOURPATH/Contact/ContactList", function(data) {
      var items = "<option selected></option>";
      $.each(data, function(i, item) {
        items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
      });
      $("#ContactID").html(items);
  });
</script>

The above function calls the ContactList method, which returns a ListItem collection. You then loop through the result, and add the options. Finally, the html contents of the dropdownlist are set. The MVC method that returns the contact list looks like this:

1
2
3
4
5
6
7
8
9
public ActionResult OrganizationList()
{
  Contact[] contacts = Contact.FindAll();
  if (HttpContext.Request.IsAjaxRequest())
  {
    return Json(new SelectList(contacts, "ID", "FullName"));
  }
  return View(contacts);
}




Abstract: 
Dynamic DropDownLists allows the user to select an item from the first dropdownlist which populates the second dropdownlist based on the selection of the first dropdownlist. In this article we are going to demonstrate how to implement dynamic dropdowns using ASP.NET MVC 3 framework. 

Creating the ViewModel: 

The first step is to create a ViewModel which will represents the elements on the View. Our ViewModel revolves around the relationship between the category and products. The user will select a category from a dropdownlist which will populate all the corresponding products in another dropdownlist. The implementation bellows shows the ArticleEditViewModel: 

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel.DataAnnotations;
04 using System.Linq;
05 using System.Web;
06 using System.Web.Mvc;
07  
08 namespace MvcApplication1.ViewModels
09 {
10   public class ArticleEditViewModel
11   {
12     private List<SelectListItem> _categories = new List<SelectListItem>();
13     private List<SelectListItem> _products = new List<SelectListItem>();
14  
15     [Required(ErrorMessage = "Please select a category")]
16     public string SelectedCategory { get; set; }
17  
18     [Required(ErrorMessage = "Please select a product")]
19     public string SelectedProduct { get; set; }
20  
21     public List<SelectListItem> Products
22     {
23       get { return _products;  }
24     }
25  
26     public List<SelectListItem> Categories
27     {
28       get
29       {
30         _categories.Add(new SelectListItem(){ Text = "Ruby", Value = "1"});
31         _categories.Add(new SelectListItem(){ Text = "JavaScript",Value="2"});
32  
33         return _categories;
34       }
35     }
36  
37   }
38 }


As, you can see that to keep the demo simple we have hard-coded the categories. In the next section we will demonstrate how to populate the categories dropdownlist using the ArticleEditViewModel. 

Populating Categories DropDownList: 

The Index action of the HomeController returns the new ArticleEditViewModel to the view. The view uses the Categories property of the ArticleEditViewModel to populate the dropdownlist. The Index action is shown below: 

1  public ActionResult Index()
2     {
3         
4       return View(new ArticleEditViewModel());
5     }


The DropDownList is populated using the code below: 

1 <text>Select a category: </text> @Html.DropDownListFor(x => x.SelectedCategory, new SelectList(Model.Categories,"Value","Text"),"Please Select a category")
2  
3 @Html.ValidationMessageFor(x => x.SelectedCategory)
4    


The DropDownList is bind to the SelectedCategory property of the ViewModel. The SelectedCategory property is also decorated with the [Required]attribute which makes sure that the SelectedCategory is not left blank or on the default item. The screenshot below shows the validation being fired when the Categories DropDownlist is left at the default option and the view is submitted. 



The validation is fired because the default option "Select a category" does not have any value associated with it. ASP.NET MVC framework tries to bind the empty string with the SelectedCategory property but fails since the SelectedCategory is marked with [Required] attribute.  
 
Fetching the Products and Populating the Dependent DropDownList: 

Our next task is to get the selected category and then fetch the associated products using the categoryId. This will be performed by an ajax call using our beloved jQuery library. The implementation below shows the details. 

01 <script language="javascript" type="text/javascript">
02  
03   $(document).ready(function () {
04  
05     $("#SelectedCategory").change(function () {
06  
07  
08       $.get('/Home/GetProductsForCategory/' + $(this).val(), function (response) {
09  
10         var products = $.evalJSON(response);
11         var ddlSelectedProduct = $("#SelectedProduct");
12  
13         // clear all previous options
14         $("#SelectedProduct > option").remove();
15  
16         // populate the products
17  
18         for (i = 0; i < products.length; i++) {
19  
20           ddlSelectedProduct.append($("<option />").val(products[i].Value).text(products[i].Text));
21         }
22  
23  
24       });
25  
26  
27     });
28  
29   });
30  
31  
32 </script>

for more plz visit this
http://www.highoncoding.com/Articles/770_Implementing_Dynamic_DropDownList_in_ASP_NET_MVC_3_Framework.aspx

http://277hz.co.uk/Blog/Show/10/drop-down-lists-in-mvc--asp-net-

hope this will help u
dipa ahuja replied to A S on 14-Aug-11 01:24 PM
Untitled document
For that you have to set the Dropdownlist Autopost=True 
and implement the selectedIndexChanged Event

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
     string s = DropDownList1.SelectedValue.ToString();
     SqlConnection conn = new SqlConnection();
     conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
     SqlDataAdapter da = new SqlDataAdapter("select product from table1 where catagory='" + s + "'", conn);
     DataSet ds = new DataSet();
 
     da.Fill(ds); // Fill the dataset
     DropDownList2.DataSource = ds;
     DropDownList2.DataTextField = "product";
     DropDownList2.DataValueField = "product";
 
     DropDownList2.DataBind();
   }
   //Bind price
   protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
   {
     string s = DropDownList2.SelectedValue.ToString();
     SqlConnection conn = new SqlConnection();
     conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
     SqlDataAdapter da = new SqlDataAdapter("select price from table1 where product='" + s + "'", conn);
     DataSet ds = new DataSet();
 
     da.Fill(ds); // Fill the dataset
     DropDownList3.DataSource = ds;
     DropDownList3.DataTextField = "price";
     DropDownList3.DataValueField = "price";
 
     DropDownList3.DataBind();
   }
Ravi S replied to A S on 14-Aug-11 02:17 PM
HI

In your view:

@Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))

where SiteId is a property of your view model which will receive the selected site id when the form is submitted.

and then you could populate this dropdown using AJAX:

$(function() {
    $
.getJSON('@Url.Action("GetSite", "Pedido")', function(result) {
       
var ddl = $('#SiteId');
        ddl
.empty();
        $
(result).each(function() {
            ddl
.append(
                $
('<option/>', {
                    value
: this.Id
               
}).html(this.Nome)
           
);
       
});
   
});
});

and the controller action that would return the JSON data:

public ActionResult GetSite()
{
   
var sites = new[]
   
{
       
new { Id = "1", Nome = "site 1" },
       
new { Id = "2", Nome = "site 3" },
       
new { Id = "3", Nome = "site 3" },
   
};
   
return Json(sites, JsonRequestBehavior.AllowGet);
}

refer
http://forums.asp.net/p/1269514/2395348.aspx
http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx
Riley K replied to A S on 14-Aug-11 10:51 PM

 
Hi,

      I will show you how to create a cascading dropdown list , you modify according to your requirement

 As always you start with a model: 

  
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()
      });
    }
  }
}

Create a Controller

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
    );
  }
}

And Finally create a View

@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>

Also check these links for more examples

http://msprogrammer.serviciipeweb.ro/2011/02/13/asp-net-mvc-jquery-and-razor-cascading-dropdown-retrieving-partial-views-json-send-objects-handling-errors/

http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx



Radhika roy replied to A S on 15-Aug-11 02:55 AM
Follow this example-

Create a new ASP.NET MVC Web Application;

Right-click on the Models folder and select Add > New Item;

From the Add New Item dialog, select LINQ to SQL classes. Name it MyModel.dbml and click Add;

Picture 1 - Create a new LINQ to SQL file

Select the connection you want to use on the Server Explorer Window, expand it and select the tables you want to use;

Drag and drop them onto the dbml file surface. For this example I am using a database that has two tables: Product and Category;

Picture 2 - Product and categories tables added to the dbml file

Right-click the Controllers folder and select Add > Controller. Name it ProductController and hit the Add button;

Picture 3 - New controller class

A new controller class is created it. Open it. We are going to add an action method called Selector that will perform a LINQ query to retrieve a list of products. We are going to save it to the ViewData dictionary and request a view to be rendered;

public class ProductController : Controller
{
  MyModelDataContext _ctx = new MyModelDataContext();

  public ActionResult Selector()
  {
    var products = from prod in _ctx.products
                select prod;

    ViewData["ProductList"] = products;

    return View();
  }
}

Right-click the action method we’ve just created and select Add View (or just press ctrl + M, V). On the Add View dialog, name it Selector and keep the first two checkboxes unchecked. Hit the Add button;

Picture 4 - Create the View for our selector

On the View we are going to use the DropdownList HtmlHelper method to render the dropdownlist control using the list of products added to the ViewData dictionary by our Selector action method. The object used to bind an IEnumerable object to a dropdownlist control is the SelectList. There an explanation about it on http://ittecture.wordpress.com/2009/04/21/tip-of-the-day-189-aspnet-mvc-dropdownlists/. We are going also to add a submit button so we can catch the selected item on the controller class. The Html markup will be similar to the following:

<% using (Html.BeginForm()) { %>
  <%= Html.DropDownList(“lstProducts”, new    SelectList((IEnumerable)ViewData["ProductList"], “ID”, “Name”)) %>
  <input type=”submit” value=”Submit” />
<% } %>

Let’s add an action method that handles the post actions on this view so we can catch the selected product id:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Selector(FormCollection form)
{
  /// Gets the selected product.
  int productID = Convert.ToInt32(form["lstProducts"]);

  [...]
}

Build and run the application. Navigate to http://localhost:<Port Number>/Product/Selector . The dropdownlist control is loaded and displays the product name.

Picture 5 - The product selector in action

You may hit the submit button and check the product id on the Selector action method that handles the post action.