【问题标题】:How to return a list to the controller based on checkbox checked?如何根据选中的复选框将列表返回给控制器?
【发布时间】:2014-07-03 08:20:23
【问题描述】:

我在 razor 视图中有一个数据表,我为表中的每一行添加了一个复选框。 我正在尝试将选中的列表返回到我在控制器中的发布操作。 但是,模型在回发时显示为 null。

模型在视图中..

  @model IPagedList<TrackerModel>

在控制器中发布 actionResult....

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

表格标签应用在另一个中,因为表格是部分的..

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

跟踪器视图模型..

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

}

所有校准...

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

所有校准视图...

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

如果我从 post actionResult 中删除 IList,我只会得到第一个选定的模型。 我做错了什么??

【问题讨论】:

  • 请出示您的form [用于发帖的)代码。
  • 如何在表单视图中编写模型?
  • 在不知道 TrackerModel 和视图的情况下很难判断 ....
  • Html.RenderAction("AllCalibrations"); 怎么样。它根本什么都说不出来。我们还需要看到这一行动。
  • 抱歉,我不想发布超出要求的代码,希望现在更清楚。

标签: c# html asp.net-mvc-3 razor


【解决方案1】:

我所做的是在包含所选记录列表的视图中隐藏输入,然后将其作为控制器操作的参数...

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

使用附加到复选框的 javascript 填充隐藏输入,即在单击复选框时将 id 添加到隐藏输入,然后在控制器操作上,您可以将其作为字符串访问;我认为它甚至会自动将逗号放在值之间,使用类似于 selectrow 函数的东西,它将遍历网格并将 selectedrow ids 放入隐藏的输入中......

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

编辑: 忘记每个循环并阅读this example on how to get the selected row data 然后获取 ID,并将其存储在隐藏的输入中,然后在控制器操作上发布后,您只需获取隐藏的输入值。

【讨论】:

  • 你能提供更多的例子来代替“//stuff”吗?
  • @mkell 如果还不算太晚...网格中内置的 mvcs 在功能上各不相同...看看 jqgrid...trirand.net/demo/aspnet/mvc/jqgrid
  • 恐怕为时已晚,这个应用程序已经上线了。我不想进行任何会导致花费大量时间进行测试的重大更改!但我仍然查看链接。
猜你喜欢
  • 2020-06-07
  • 2015-05-29
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
相关资源
最近更新 更多