Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are many ways and saying which is the best would be subjective and might not work in your scenario which by the way you forgot to describe in your question. Here's how I do it:</p> <p>Model:</p> <pre><code>public class MyViewModel { public string SelectedItem { get; set; } public IEnumerable&lt;Item&gt; Items { get; set; } } public class Item { public string Value { get; set; } public string Text { get; set; } } </code></pre> <p>Controller:</p> <pre><code>public class HomeController : Controller { public ActionResult Index() { var model = new MyViewModel { // TODO: Fetch this from a repository Items = new[] { new Item { Value = "1", Text = "item 1" }, new Item { Value = "2", Text = "item 2" }, new Item { Value = "3", Text = "item 3" }, } }; return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { if (!ModelState.IsValid) { // redisplay the view to fix validation errors return View(model); } // TODO: The model is valid here =&gt; // perform some action using the model.SelectedItem // and redirect to a success page informing the user // that everything went fine return RedirectToAction("Success"); } } </code></pre> <p>View (<code>~/Views/Home/Index.cshtml</code>):</p> <pre><code>@model MyApp.Models.MyViewModel @{ Html.BeginForm(); } @Html.EditorForModel() &lt;input type="submit" value="OK" /&gt; @{ Html.EndForm(); } </code></pre> <p>Editor template (<code>~/Views/Home/EditorTemplates/MyViewModel.cshtml</code>):</p> <pre><code>@model MyApp.Models.MyViewModel @Html.DropDownListFor(x =&gt; x.SelectedItem, new SelectList(Model.Items, "Value", "Text")) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload