添加复选框上MVCcontrib网格每一行 [英] Adding check boxes to each row on MVCcontrib Grid

查看:99
本文介绍了添加复选框上MVCcontrib网格每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加一个复选框,一个网格MVCcontrib的每一行。那么当窗体发布找出被选择哪些记录?这个搜索时,我没有找到太多。
谢谢

How can I add a checkbox to each row of a MVCcontrib grid. then when the form is posted find out which records were selected? I Am not finding much when searching for this. Thank you

推荐答案

下面是你如何才能够着手:

Here's how you could proceed:

型号:

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", IsInStock = false },
            new Product { Id = 4, Name = "product 4", IsInStock = true },
        };
        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>

最后这里是一个辅助方法,你可以用它来生成此复选框:

And finally here's a helper method you could use to generate this checkbox:

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());
    }
}

这简化了的部分:

Which simplifies the partial:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.Product>" %>
<td><%: Html.EditorForIsInStock() %></td>

这篇关于添加复选框上MVCcontrib网格每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆