项目列表始终为空MVC 5

时间:2018-10-23 11:15:27

标签: asp.net asp.net-mvc-5

我陷入了这个问题,无法解决。

这是我的ViewModel

public class AddOrderReceive
{
  public string item_name { get; set; }
  public DateTime? date_received { get; set; }
  public decimal? quantity_received { get; set; }
  public bool IsSelected { get; set; }
  public decimal? item_rate { get; set; }
}

这是我的View

    @model List<newtest.Models.AddOrderReceive>

    @if(Model != null && Model.Count > 0)
    {
      for(var i = 0; i < Model.Count; i++)
        {
          <tr>
              @if(Model[i].quantity_remaining == 0)
              {
                <td colspan="6" class="text-center">Already Sent</td>
              }
              else
              {
                @Html.HiddenFor(r => Model[i].item_id)
                <td>@Html.CheckBoxFor(r => Model[i].IsSelected)</td>
                <td>@Html.EditorFor(r => Model[i].item_rate)</td>
              }
           </tr>
        }
  }  

最后,这是我的Controller

 [HttpGet]
    public ActionResult AddRAR(int? my_id)
    {
      try
      {
        var get_items = (from or in db.orders
                         where or.id == my_id
                         select new AddOrderReceive()
                         {
                           item_name = or.item_name,
                           quantity_received = or.quantity_receive,
                           date_received = or.date_receive,
                           order_receive_id = or.order_receive_id 
                         }).ToList();

foreach(var t in get_items)
 {
   var get_remain = (from ra in db.order_detail
                     where ra.contract_id == t.ca_id && ra.order_receive_id == t.order_receive_id 
                     select new
                     {
                       consump_quantity = ra.consump_quantity
                     });
                    t.quantity_remaining = t.quantity_received - get_remain.Sum(r => r.consump_quantity) ?? t.quantity_received;

                }
        return View(get_items);


    }
     catch(Exception ex)
     {

     }


    }  


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddReceivng(List<AddOrderReceive> rc_form)
{
       //Some Logic
}

问题在于,每当我发布表单时,该表单始终为null。但是当我删除此块时:

@if(Model[i].quantity_remaining == 0)
{
    <td colspan="6" class="text-center">Already Sent</td>
}  

它开始工作。我不知道出什么问题了。我到处搜索过,但仍然无法在这里找出问题。

1 个答案:

答案 0 :(得分:0)

如果您的@if(Model[i].quantity_remaining == 0)代码块在第一次迭代中执行,则意味着您的集合索引器不会基于零。 DefaultModelBinder要求集合索引器从零开始并且是连续的。

您可以通过为索引器包括隐藏的输入来覆盖此行为。还请注意,<input>不是<tr>的有效子元素,应放在<td>元素内。

for(var i = 0; i < Model.Count; i++)
{
    @if(Model[i].quantity_remaining == 0)
    {
        <td colspan="6" class="text-center">Already Sent</td>
    }
    else
    {
        <td>
            <input type="hidden" name="Index" value="@i" /> // Add this
            @Html.HiddenFor(r => r[i].item_id)
            @Html.CheckBoxFor(r => r[i].IsSelected)
        </td>
        <td>@Html.EditorFor(r => r[i].item_rate)</td>
    }
}