Best Way to Let User Select from Open-Ended List of Strings in ASP.NET MVC
I have a dynamic list of 10-25 strings and would like to present them as checkboxes in an ASP.NET MVC application. What's the easiest way to do this? Do I have to create a list of ViewModel stru开发者_运维百科ctures that pair booleans with strings? After a form post, I want to submit the checked values and resolve them to the list of strings again on the server side.
Thanks!
Do I have to create a list of ViewModel structures that pair booleans with strings?
That would indeed be the best way and what I would recommend you:
Model:
public class MyViewModel
{
public string Label { get; set; }
public bool IsSelected { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// Normally that comes from a respotiroy or something
var model = Enumerable.Range(1, 25).Select(x => new MyViewModel
{
Label = "item " + x
});
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// TODO: process your model. It will contain a list of all items
// along with their selected values
return View(model);
}
}
View (~/Views/Home/Index.cshtml
):
@model IEnumerable<MyViewModel>
@using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
<input type="submit" value="OK" />
}
and finally the editor template which will be rendered for each element of your model (~/Views/Home/EditorTemplates/MyViewModel.cshtml
):
@model MyViewModel
<tr>
<td>
@Html.LabelFor(x => x.IsSelected, Model.Label)
@Html.HiddenFor(x => x.Label)
</td>
<td>
@Html.CheckBoxFor(x => x.IsSelected)
</td>
</tr>
If you want to get the values of the checkboxes, and you want a strongly typed view, then yes. You need a viewmodel that has an IEnumerable<ViewModel>
where ViewModel has a pairing of boolean and string.
Just make sure to use DisplayForModel to render your model, or you won't get the built-in collection handling.
EDIT: As usual, Darin's answer is much more complete than mine. ;)
精彩评论