如何在MVCcontrib网格的每一行添加一个复选框.那么当表单发布时,会找出哪些记录被选中?寻找这个时候找不到很多东西.
谢谢
谢谢
解决方法
以下是您可以如何处理:
模型:
public class Product { public int Id { get; set; } public string Name { get; set; } public bool IsInStock { get; set; } }
控制器:
public class HomeController : Controller { public ActionResult Index() { var products = new[] { new Product { Id = 1,Name = "product 1",IsInStock = false },new Product { Id = 2,Name = "product 2",IsInStock = true },new Product { Id = 3,Name = "product 3",new Product { Id = 4,Name = "product 4",}; return View(products); } [HttpPost] public ActionResult Index(int[] isInStock) { // The isInStock array will contain the ids of selected products // TODO: Process selected products return RedirectToAction("Index"); } }
视图:
<% using (Html.BeginForm()) { %> <%= Html.Grid<Product>(Model) .Columns(column => { column.For(x => x.Id); column.For(x => x.Name); column.For(x => x.IsInStock) .Partial("~/Views/Home/IsInStock.ascx"); }) %> <input type="submit" value="OK" /> <% } %>
部分:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %> <!-- TODO: Handle the checked="checked" attribute based on the IsInStock model property. Ideally write a helper method for this --> <td><input type="checkBox" name="isInStock" value="<%= Model.Id %>" /></td>
最后,这里是一个帮助程序,您可以使用它来生成此复选框:
using System.Web.Mvc; using Microsoft.Web.Mvc; public static class HtmlExtensions { public static MvcHtmlString EditorForIsInStock(this HtmlHelper<Product> htmlHelper) { var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttribute("type","checkBox"); tagBuilder.MergeAttribute("name",htmlHelper.NameFor(x => x.IsInStock).ToHtmlString()); if (htmlHelper.ViewData.Model.IsInStock) { tagBuilder.MergeAttribute("checked","checked"); } return MvcHtmlString.Create(tagBuilder.ToString()); } }
这简化了部分:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %> <td><%: Html.EditorForIsInStock() %></td>