How to return a list to the controller based on checkbox checked?

I have a table of data in a razor view, to which I added a checkbox for each row in the table. I'm trying to return the checked list to my post action in the controller. However the model shows as null on post back.

Model in view..

  @model IPagedList<TrackerModel>

Post actionResult in controller....

     [HttpPost]
    public ActionResult Index(IList<TrackerModel> model)
    {
        return View(model);
    }

The form tag is applied in another as the table is in a partial..

      <div id="all-calibrations-grid" class="pull-left tracker-container">
    @using (Html.BeginForm(FormMethod.Post))
   {
        {Html.RenderAction("AllCalibrations");}
         }
    </div>

Tracker ViewModel..

   public class TrackerModel
{
    public int Id { get; set; }
    public string EquipmentID { get; set; }
    public string EquipmentDescription { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime? ExpectedReturnedToCustomer { get; set; }
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime? DateOfCalibration { get; set; }
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime? NextDueDate { get; set; }

    public bool StatusChange { get; set; } //01/07/2014

    public string Status { get; set; }
    public string CustomerName { get; set; }

}

All calibrations ...

  [RoleAuthorization(Roles = "Customer User Passive,LTS User Passive")]
    public PartialViewResult AllCalibrations(int? page, IPrincipal user)
    {
        int totalRecords;

        // the filter model is fully populated
        var filter = (CalibrationFilter)Session["_Filter"];
        filter.PageSize = ((CalibrationFilter)Session["_Filter"]).PageSize;
        filter.Page = page.HasValue ? page.Value - 1 : 0;

        IList<Calibration> calibrationList;

        if (user.IsInRole("LTS User Passive"))
        {
            LtsUser ltsUser = _ltsUserRepo.GetUser(user.Identity.Name);

            // access the required data from the calibration repository
            calibrationList = _calRepo.GetAllCalibrations(ltsUser.Customers, out totalRecords, filter);
        }

        else
        {
            CustomerUser custUser = _custUserRepo.GetUser(user.Identity.Name);
            var customer = new List<Customer> { _custRepo.GetCustomer(custUser.Customer.Name) };

            // access the required data (for a specific customer) from the calibration repository
            calibrationList = _calRepo.GetAllCalibrations(customer, out totalRecords, filter);
        }

        var customerViewList = Mapper.Map<IList<Calibration>, IList<TrackerModel>>(calibrationList);

        IPagedList<TrackerModel> pagedList = customerViewList.ToPagedList(filter.Page, filter.PageSize, totalRecords);

        return PartialView("AllCalibrations", pagedList);
    }

All Calibrations View...

@using InstrumentTracker.ViewModels.TrackerModels
@using MvcPaging

@model IPagedList<TrackerModel>
@{
 Layout = null;
  AjaxOptions ajaxOpts = new AjaxOptions
 {
    UpdateTargetId = "all-calibrations-grid",
    HttpMethod = "POST"
    };
}


@RenderPage("StatusLegend.cshtml")


<span>Displaying @Model.ItemStart - @Model.ItemEnd of @Model.TotalItemCount Calibrations</span>


<table id="all-calibrations" class="grid tracker-grid">
 <colgroup>
    <col class="workno-data">
    <col class="equipmentId-data">
    <col class="equipmentDesc-data">
    <col class="calDate-data">
    <col class="nextDueDate-data">
    <col class="status-data">
 </colgroup>



 <thead>
     <tr>

       @* ADDED 23/06/2014 *@
              @if (this.User.IsInRole("LTS Admin"))
              {
           <th id="SelectHeader">

           <input type="submit" class="styledbutton" value="Save" /></th>
              }

        <th>Work<br />No.</th>
        <th>ID</th>
        <th>Description</th>
        <th>Calibrated<br />On</th>
        <th>Next<br />Due</th>
        <th id="status-header">Status<a id="status-help" href="#">?</a></th>
        @*Add the following to <th> tag if ? does not display correctly - style="text-overflow:clip;"*@

        @* the customer column is only shown for LTS users since customer only see 1 customers data *@
        @if (this.User.IsInRole("LTS User Passive"))
        {
            <th>Customer</th>
        }
      </tr>
 </thead>
    <tbody>
    @* iterate through each calibration shown on this page *@
    @for (int index = 0; index < Model.Count(); index++)
    {
        @Html.HiddenFor(m => Model.ElementAt(index).Id)
        @Html.HiddenFor(m => Model.ElementAt(index).EquipmentID)
        @Html.HiddenFor(m => Model.ElementAt(index).EquipmentDescription)
        @Html.HiddenFor(m => Model.ElementAt(index).DateOfCalibration)
        @Html.HiddenFor(m => Model.ElementAt(index).NextDueDate)
         @Html.HiddenFor(m => Model.ElementAt(index).CustomerName)

        <tr>
         @*<th name="SelectCells" style="display:none;"><input type="checkbox" name="selectedCals" value="<m => Model.ElementAt(index).Id>"/></th>*@
                                   @* ADDED 23/06/2014 *@
              @if (this.User.IsInRole("LTS Admin"))
              {
            <th>@Html.EditorFor(m => Model.ElementAt(index).StatusChange, new { name = "selectedCals" })</th>
              }


            @* The work number is a link to the calibration the work no. represents *@
            <td>@Html.ActionLink("WN–" + @Html.DisplayFor(m => Model.ElementAt(index).Id), "Index", "CalibrationViewer", new { id = Model.ElementAt(index).Id }, null)</td>
            <td>@Html.DisplayFor(m => Model.ElementAt(index).EquipmentID)</td>
            <td>@Html.DisplayFor(m => Model.ElementAt(index).EquipmentDescription)</td>
            <td>@Html.DisplayFor(m => Model.ElementAt(index).DateOfCalibration)</td>
            <td>@Html.DisplayFor(m => Model.ElementAt(index).NextDueDate)</td>
            <td>@Html.DisplayFor(m => Model.ElementAt(index).Status)</td>
            @* once again only the lts user sees the customer column data *@
            @if (this.User.IsInRole("LTS User Passive"))
            {
                <td>@Html.DisplayFor(m => Model.ElementAt(index).CustomerName)</td>
            }
         </tr>
         }
        </tbody>
     }

    </table>


    @* The page navigation for the recently completed table *@
    <div class="pager">
       @Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, ajaxOpts).Options(o => o.Action("AllCalibrations"))
    </div>

If I remove the IList from the post actionResult, I just get the first selected model. What am I doin wrong ??


What I do is have a hidden input in the view that holds a list of the selected records and then have that as a parameter on the controller action...

<input id="selectedRecords" name="selectedRecords" type="hidden" />

Populate the hidden input using javascript attached to the checkboxes, ie add an id to the hidden input when a checkbox is clicked, then on the controller action you can access it as a string; i think it even puts commas inbetween values automagically, using something like a selectrow function that will loop through the grid and put the selectedrow ids into the hidden input...

$.each(checkedIds, function (value) {
    // stuff
});

EDIT: Forget that each loop and have a read of this example on how to get the selected row data Then get the ID, and store it in the hidden input, then on post on the controller action you simply get the hidden input value.

链接地址: http://www.djcxy.com/p/53970.html

上一篇: 模型在Child Partial页面MVC5上的帖子上为空

下一篇: 如何根据选中的复选框将列表返回给控制器?