As always, start with the model (actually start with the unit test, but not for this here):
public class MyModel { public string SelectedItem { get; set; } public IEnumerable<SelectListItem> Items { get; set; } }
Then the controller:
public class HomeController : Controller { public ActionResult Index() { var items1 = new[] { new { Value = "1", Text = "Manual Item 1" }, new { Value = "2", Text = "Manual Item 2" }, }; // TODO: Go fetch those from your repo1 var items2 = new[] { new { Value = "3", Text = "DS1 Item 1" }, new { Value = "4", Text = "DS1 Item 2" }, }; // TODO: Go fetch those from your repo2 var items3 = new[] { new { Value = "5", Text = "DS2 Item 1" }, new { Value = "6", Text = "DS2 Item 2" }, }; var items = items1.Concat(items2).Concat(items3); var model = new MyModel { Items = new SelectList(items, "Value", "Text") }; return View(model); } }
And finally, a strongly typed model representation:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyApp.Models.MyModel>" %> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%= Html.DropDownListFor(x => x.SelectedItem, Model.Items) %> </asp:Content>
You will probably define a mediation type to avoid the anonymous types that I used for brevity.
Note. If your original question was about using OPTGROUP , then ignore my answer and make your intention clear so that you can get a more tailored answer.
source share