Assuming that you mean to have the second drop-down's values updated each time a different value is selected in the first drop-down, one way to do it is via jQuery, JSON, a view model and some controller actions (note this doesn't implement best practices like not having database calls in controller actions and extracting JS from the view and putting it into a module):
Entities:
namespace DataModel
{
public class Item
{
[Id]
public int ItemId {get; set;}
public string ItemText {get; set;}
}
public class Attribute
{
[Id]
public int AttributeId {get; set;}
public string AttributeText {get; set;}
}
}
(omitting DbContext
code)
Controller actions:
[HttpGet]
public ActionResult TestDropdown()
{
using(var context = new YourDbContext()) // it's good practice to use the using() statement to dispose of the DbContext's resources right when it's finished, rather than setting a class-level variable
{
var model = new Models.TestDropdownViewModel();
// gets all the items; you might want to filter for items that you want to display
model.Items = context.Items.ToList().Select(i => new SelectListItem()
{
Text = i.ItemText,
Value = i.ItemId.ToString() // this is probably an ID of the row for the corresponding Item
});
model.Attributes = context.Attributes.First().Select(a => new SelectListItem
{
Text = a.AttributeText,
Value = a.AttributeId.ToString()
});
return View(model);
}
}
[HttpGet]
public JsonResult GetAttributesForItem(int selectedId)
{
using(var context = new YourDbContext())
{
var attributes = context.Attributes.Where(a => a.Item.ItemId == selectedId).ToList();
return Json(addresses.Select(a => new { Value = a.AddressId.ToString(), Text = a.Address1 }), JsonRequestBehavior.AllowGet);
}
}
View model:
using System.Web.Mvc;
using System.Collections.Generic;
namespace Models
{
public class TestDropdownViewModel
{
public IEnumerable<SelectListItem> Items { get; set; }
public IEnumerable<SelectListItem> Attributes { get; set; }
}
}
Partial View:
// make sure jQuery is loaded in your _Layout.cshtml if you're using that pattern
@model Models.TestDropdownViewModel
@{
ViewBag.Title = "TestDropdown";
}
<div>
@Html.DropDownList("Items", Model.Items, new { id = "Items" })
</div>
<br />
<div>
@Html.DropDownList("Attributes", Model.Attributes, new { id = "Attributes" })
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#Items').change(function () {
var selectedId = this.value;
$.getJSON('/GetAttributesForItem?', { id: selectedId }, function (data) {
var attributes = $('#Attributes');
var options;
$.each(data, function (index, elem) {
options += "<option value='" + elem.Value + "'>" + elem.Text + "</option>";
});
attributes.html(options);
});
});
});
</script>