【问题标题】:Select rows and pass data(ID) to next view, MVC5 C#选择行并将数据(ID)传递给下一个视图,MVC5 C#
【发布时间】:2018-05-10 13:12:01
【问题描述】:

我一直在尝试从我的数据表中选择多行(使用 EF 生成),然后将所有选定的行传递到下一个视图以执行某些操作。在将数据传递到下一个视图时,我收到以下错误:

System.NullReferenceException: '对象引用未设置为对象的实例。' 'int[]'> 类型的临时局部变量为空。

任何有关如何解决此问题的帮助将不胜感激。

下面是我的代码:

查看:

<div class="row">
  <div class="col-md-12">
    <!-- Advanced Tables -->
    <div class="panel panel-default">
      <div class="panel-heading">
        @using (Html.BeginForm()) {
        <form action="#" method="post">
          <label>Search by Company Name:</label> @Html.TextBox("SearchString")
          <input type="submit" value="Go" placeholder="Search" style="background-color: #0a9dbd; color: white; border-color: #0a9dbd;"> &nbsp; &nbsp;
          <label>Search by Card Number:</label> @Html.TextBox("searchCard")
          <input type="submit" value="Go" placeholder="Search" style="background-color: #0a9dbd; color: white; border-color: #0a9dbd;"> &nbsp; &nbsp;
          <a href="ExportToExcel">Export to Excel</a>
        </form>

        }
      </div>

      <div class="panel-body">
        <a href="@Url.Action(" Create ","CustomerView ")" class="btn btn-primary">Add Gift Card</a>
        <a href="@Url.Action(" GetBalance ", "CustomerView ")" class="btn btn-primary">Get Card Balance</a>
        <a href="@Url.Action(" PostCards ", "CustomerView ")" class="btn btn-primary">Load Cards</a>

        <br />
        <br />
        <div class="table-responsive">
          <table class="table table-striped table-bordered table-hover" id="dataTables-example">
            <thead>
              <tr>
                <th>Card ID</th>
                <th>Company</th>
                <th>Card Number</th>
                <th>Card Number 2</th>
                <th>Date Created</th>
                <th>Card Status</th>
                <th>Discount Level ID</th>
                <th>Loyalty Level ID</th>
                <th>Gift Card Enabled</th>
                <th>Loyalty Enabled</th>
                <th></th>

              </tr>
            </thead>
            <tbody>
              @foreach (var item in Model) {
              <tr>
                <td><input type="checkbox" name="ids" value="@item.CardID" /></td>
                <td>@item.CardID</td>
                <td>@item.Customer.CustomerCompanyName</td>
                <td>@item.CardNumber</td>
                <td>@item.CardNumber2</td>
                <td>@item.CardDate</td>
                <td>@item.CardStatus</td>
                <td>@item.DiscountLevelID</td>
                <td>@item.LoyaltyLevelID</td>
                <td>@item.GiftCardEnabled</td>
                <td>@item.LoyaltyEnabled</td>


                <td>
                  <a href="@Url.Action(" Edit ","CustomerView ", new {id = item.CardID} )" class="btn btn-primary"><i class="fa fa-edit "></i> Edit</a> <br />

                </td>

              </tr>
              }
            </tbody>

          </table>
          Page @(Model.PageCount
          < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page=> Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
        </div>

      </div>
    </div>
    <!--End Advanced Tables -->
  </div>
</div>

控制器:

public ActionResult PostCards(int[]ids)
        {
            var myObject = new Card();

            foreach(var id in ids)
            {
                myObject = db.Cards.Single(o => o.CardID == id);
                return RedirectToAction("LoadCards", myObject);
            }

            return View();
        }


        public ActionResult LoadCards()
        {
            return View();
        }

我需要将所选数据传递到 LoadCards 视图。

【问题讨论】:

  • 您的复选框不在&lt;form&gt; 元素内(因此它们不发布值,因此ids 参数为null)。不仅如此,您还有无效且不受支持的嵌套表单
  • 而且您的控制器方法方法无论如何都没有意义 - 您有一个带有 return RedirectToAction() 的循环,这意味着您在第一次迭代期间退出该方法。
  • 好的,谢谢。我设法弄清楚并让它工作

标签: c# asp.net-mvc


【解决方案1】:

让我们先看看你得到的 NullReference。这里的问题是没有创建正确的索引来将复选框绑定到数组。使用 for 循环而不是 foreach。 In MVC/Razor, how do I get the values of multiple checkboxes and pass them all to the controller?

要获得所需的行为:

  • foreach 更改为for 循环,以便创建用于发送数据的正确索引。
  • 在每一行中添加一个复选框,让用户选择要提交的行。
  • 您的操作应该收到每行的模型集合。这个模型总是传输 CardId 并告诉我们它是否被选中。

    public class SelectedCardModel {
    
        public int CardId { get; set; }
        public bool IsSelected {get; set;}
    }
    

在视图中:

@using (Html.BeginForm("PostCards", "CustomerView", FormMethod.Post) {
    // <table> etc ... 
    <tbody>
    @for (var i = 0; i < Model.Count; i++) {
        @{ var item = Model.ElementAt(i); }
        <tr>
            <td>
                @Html.Hidden("CardId[" + i + "]")
                @Html.CheckBox("IsSelected[" + i + "]")
            </td>
            // display other properties of item ...
            <td>@item.CardID</td>
            // ...
        </tr>
    }
    </tbody>
    </table>
    <button type="submit">Load Cards</button>
}

行动:

[HttpPost]
public ActionResult PostCards(SelectedCardModel[] selectedCards) {
    foreach(var card in selectedCards) {
        if (card.IsSelected) {
            var selectedId = card.CardId;
            // ...
        }
    }
}

【讨论】:

  • 在这种情况下不需要集合索引器 - 参数是简单类型的数组(只有复杂对象的集合才需要集合索引器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2021-07-24
相关资源
最近更新 更多