开发者

Adding check boxes to each row on MVCcontrib Grid

开发者 https://www.devze.com 2023-01-03 20:08 出处:网络
How can I add a che开发者_JAVA百科ckbox 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.

How can I add a che开发者_JAVA百科ckbox 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:

Model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsInStock { get; set; }
}

Controller:

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

View:

<% 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" />
<% } %>

Partial:

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


Dont know if this helps but I did a similar thing using the code below:

@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 + "'/>" ) );
})

My controller was then able to receive the selected checkboxlist items:

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


For resolving this in every get request I'm appending checked boxes value as comma separated string. Then retrieve the values from query string.

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


    });


In your view (say ReportList.cshtml) include your grid in a form and define an action for the form

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

Then in your controller implement your action method

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");
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消