将复选框添加到MVCcontrib Grid上的每一行

时间:2010-06-19 03:57:05

标签: c# asp.net-mvc mvcc

如何为MVCcontrib网格的每一行添加一个复选框。然后在发布表单时找出选择了哪些记录?我在寻找这个时找不到多少。 谢谢

4 个答案:

答案 0 :(得分:9)

以下是您可以继续的方式:

型号:

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>

答案 1 :(得分:3)

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

@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)

答案 2 :(得分:0)

为了在每个get请求中解析这个,我将复选框值附加为逗号分隔的字符串。然后从查询字符串中检索值。

$("#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);


    });

答案 3 :(得分:0)

在您的视图中(比如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");
    }