I am lost with the submission of listbox with multiple itmes selected and with group of checkboxes.
If that was a WebForm project it wouldn't be a problem for me.
What are the best practices and maybe some code samples that show proper submission of form in ASP.NET MVC2 that contains group of checkboxes and listbox with mutiple selected开发者_运维技巧 items?
Here is the sample of the form:
Categories: - group of checkboxes
Topics: - listbox with multiple attribute (multiple="multiple")
As always start by defining the view model:
public class MyModel
{
public bool Check1 { get; set; }
public bool Check2 { get; set; }
public IEnumerable<SelectListItem> ListItems { get; set; }
public string[] SelectedItems { get; set; }
}
Next the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
Check1 = false,
Check2 = true,
ListItems = new SelectList(new[]
{
new { Id = 1, Name = "item 1" },
new { Id = 2, Name = "item 2" },
new { Id = 3, Name = "item 3" },
}, "Id", "Name")
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// TODO: Process the model
// model.SelectedItems will contain a list of ids of the selected items
return RedirectToAction("index");
}
}
and finally the View:
<% using (Html.BeginForm()) { %>
<div>
<%: Html.LabelFor(x => x.Check1) %>
<%: Html.CheckBoxFor(x => x.Check1) %>
</div>
<div>
<%: Html.LabelFor(x => x.Check2) %>
<%: Html.CheckBoxFor(x => x.Check2) %>
</div>
<div>
<%: Html.ListBoxFor(x => x.SelectedItems, Model.ListItems) %>
</div>
<input type="submit" value="OK" />
<% } %>
精彩评论