【问题标题】:Adding check boxes to each row on MVCcontrib Grid为 MVCcontrib Grid 上的每一行添加复选框
【发布时间】:2010-06-19 03:57:05
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-mvc mvcc


    【解决方案1】:

    您可以按照以下方式进行操作:

    型号:

    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>
    

    最后还有一个帮助方法,您可以使用它来生成此复选框:

    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>
    

    【讨论】:

    【解决方案2】:

    不知道这是否有帮助,但我使用下面的代码做了类似的事情:

    @Html.Grid(Model.PagedModel).AutoGenerateColumns().Columns(column => {
    column.For(a => Html.ActionLink("Edit", "Edit", new { a.ID })).InsertAt(0).Encode(false);
    column.Custom(a => Html.Raw("<input type='checkbox' name='resubmit' value='" + a.ID + "'/>" ) );
    })
    

    然后我的控制器能够接收选定的复选框列表项:

    [HttpPost]
    public ViewResult List(string[] resubmit)
    

    【讨论】:

    • 这是一个快速而肮脏的解决方案。但有时这就是你所需要的:)
    【解决方案3】:

    为了在每个获取请求中解决此问题,我将复选框值附加为逗号分隔的字符串。然后从查询字符串中检索值。

    $("#pageLayout a").click(function () {
            //Check for the click event insed area pageLayout
            //get the href of link
            var link = $(this).attr('href');
            var apps = '';
    
            //for all the checkbox get the checked status
            $("input:checkbox").each(
                function () {
                    if ($(this).attr('name') != 'IsChecked') {
                        if (apps != '') {
                            apps = apps + ',' + $(this).attr('name') + '=' + $(this).is(':checked');
    
                        }
                        else {
                            apps = $(this).attr('name') + '=' + $(this).is(':checked');
                        }
                    }
    
                }
                )
    
    
            //Used to check if request has came from the paging, filter or sorting. For the filter anchor href doesnt haave
            //any query string parameter. So for appending the parameter first ? mark is used followed by list of query string 
            //parameters. 
            var index = link.lastIndexOf('?');            
    
            //If there is no question mark in the string value return is -1
            if (index == -1) {
                //url for the filter anchor tag
                //appList hold the comma sep pair of applicationcode=checked status
                link = link + '?appList=' + apps + '&profileName=' + $('#ProfileName').val();
            }
            else {
                //url for sorting and paging anchor tag                
                link = link + '&appList=' + apps + '&profileName=' + $('#ProfileName').val();
    
            }
    
    
            //Alter the url of link
            $(this).attr('href', link);
    
    
        });
    

    【讨论】:

      【解决方案4】:

      在您的视图中(例如 ReportList.cshtml)将您的网格包含在表单中并为表单定义一个操作

      <html>
      <form action="/SubmitReportList">
                  @{Html.Grid((List<NetSheet.Models.Report>)ViewData["ReportList"])
             .Sort((GridSortOptions)ViewData["sort"])
             .Attributes(id => "grid", @class => "grid")
      
             .Columns(column =>
             {
                  column.For(c => Html.CheckBox("chkSelected", new { @class = "gridCheck",   @value = c.ReportId }))
                  .Named("").Encode(false)
                  .Attributes(@class => "grid-column");
      
      
      column.For(c => c.ReportName)
                    .Named("Buyer Close Sheet Name")
                    .SortColumnName("ReportName")
                     .Attributes(@class => "grid-column");
      
             })
             .Render();}
      
      <input type="submit" name=" DeleteReports" id=" DeleteReports" value="Delete" class="btnSubmit"/>
      
      </form>
      </html>
      

      然后在你的控制器中实现你的动作方法

      public ActionResult SubmitReportList (string ReportListSubmit, IList<string> chkSelected){
          // The IList chkSelected will give you a list of values which includes report ids for the selected reports and “false” for the non-selected reports. You can implement your logic accordingly. 
          return View("ReportList");
          }
      

      【讨论】:

        猜你喜欢
        • 2017-03-20
        • 1970-01-01
        • 2022-07-20
        • 2019-05-23
        • 1970-01-01
        • 2021-04-29
        • 2011-04-21
        • 1970-01-01
        • 2019-11-14
        相关资源
        最近更新 更多