2010-06-19 30 views

Respuesta

9

Así es como se podría proceder:

Modelo:

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

controlador:

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

Vista:

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

parcial:

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

Y finalmente aquí es un método de ayuda se puede utilizar para generar esta casilla:

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

lo que simplifica el parcial:

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

Muy bonito voy a darle una oportunidad. ¡Gracias! – twal

+0

@Darin Dimitrov ¿Sería posible usar un objeto complejo en el POST en lugar de una matriz de enteros? Vea su respuesta: http://stackoverflow.com/questions/5284395/checkboxlist-in-mvc3-view-and-get-the-checked-items-passed-to-the-controller – Rookian

+0

@Rookian, por supuesto que es posible . –

0

Para resolver esto en cada conseguir petición estoy se agrega el valor de cuadros marcados como una cadena separada por comas. Luego recupere los valores de la cadena de consulta.

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

No sé si esto ayuda, pero lo hice una cosa similar con el siguiente código:

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

Mi controlador fue entonces capaz de recibir los artículos CheckBoxList seleccionados:

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

Esto es una solución rápida y sucia Pero a veces eso es todo lo que necesitas :) – th1rdey3

0

En su vista (por ejemplo, ReportList.cshtml) incluye su cuadrícula en un formulario y define una acción para el formulario

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

Luego, en el controlador de poner en práctica su método de acción

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