Example of DropDownListFor in ASP.NET MVC DropDownList Control
This example demonstrates the strongly-typed helper of DropDownList. Edit the DropDownList's value and click the 'Submit' button to pass the modified value to controller.
@Html.UiDropDownListFor(model => model.val, new UiDropDownListOptions { Items = Model.data.Select(text => new UiListItem(text, text)).ToList(), Placeholder = "e.g. Basketball" })
@Html.UiButton(new UiButtonOptions { Id = "btn", Text = "Submit", Type = UiButtonType.Submit, Color = UiButtonColor.Primary })
<style>
#wrapper { max-width: 246px; margin: 30px auto; padding-top: 50px; }
#submitbutton { margin-top: 20px; margin-left: 65px; }
.field-validation-error { color: red; }
</style>
@using Lumen.UI.Mvc.Demo.Controllers
@model DropdownsDemoController.DropdownlistModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="control-section">
<div id="wrapper">
@Html.UiDropDownListFor(model => model.val, new UiDropDownListOptions { Items = Model.data.Select(text => new UiListItem(text, text)).ToList(), Placeholder = "e.g. Basketball" })
<div>
@Html.ValidationMessageFor(model => model.val)
</div>
<div id="submitbutton">
@Html.UiButton(new UiButtonOptions { Id = "btn", Text = "Submit", Type = UiButtonType.Submit, Color = UiButtonColor.Primary })
</div>
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class DropDownListController : Controller
{
// The page is Views/DropDownList/DropdownlistFor.cshtml; it draws what ViewData holds.
public ActionResult DropdownlistFor()
{
DropdownlistModel model = new DropdownlistModel();
model.data = datasource;
model.val = "Badminton";
return View(model);
}
[HttpPost]
public ActionResult DropdownlistFor(DropdownlistModel model)
{
// the posted value is obtained from the model
return View(model);
}
public class DropdownlistModel
{
[Required(ErrorMessage = "Value is required")]
public string val { get; set; }
public string[] data { get; set; }
}
private static readonly string[] datasource = new string[] { "Badminton", "Cricket", "Football", "Golf", "Tennis" };
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
In this sample, the DropDownList is rendered with strongly-typed helper (FOR control) and bound its value from controller using model binding. The modified value is bond to controller action "DropDownListFor" when submitting a page.