另一个null集合正在传递给MVC控制器



我需要额外的眼睛才能看到:

  1. 当我试图将一个对象集合传递给MVC控制器时,我做错了什么,结果得到的只是sgList=null
  2. 如何进行检查,以便只保存正在更改的行。

    [HttpPost]
    public ActionResult Index(IList<EZone_ServiceGroup> sgList)
    {
        try
        {
            foreach (EZone_ServiceGroup sg in sgList)
                svcGroupRepo.UpdateServiceGroup(sg);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
    

视图:

@model IEnumerable<KTCEzone.Domain.Entities.EZone_ServiceGroup>
@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
    <div class="row">
        <table class="table table-condensed table-bordered table-hover table-striped small" id="sgTable">
            <tr>
                <th class="col-sm-12">@Html.DisplayNameFor(model => model.GroupID)</th>
                <th>@Html.DisplayNameFor(model => model.GroupName)</th>
                <th>@Html.DisplayNameFor(model => model.ParentGroupID)</th>
                <th>@Html.DisplayNameFor(model => model.Active)</th>
                <th>@Html.DisplayNameFor(model => model.OrderIndex)</th>
            </tr>
            @{var items = Model.ToArray();}
            @for (int i = 0; i < items.Length; i++)
            {
                <tr>
                    <td>@Html.DisplayFor(modelItem => items[i].GroupID)</td>
                    <td>@Html.EditorFor(modelItem => items[i].GroupName) </td>
                    <td>@Html.EditorFor(modelItem => items[i].ParentGroupID) </td>
                    <td>@Html.CheckBoxFor(modelItem => items[i].Active) </td>
                    <td>@Html.EditorFor(modelItem => items[i].OrderIndex) </td>
                </tr>
            }
        </table>
    </div>
}

型号:

public class EZone_ServiceGroup
{
    public int GroupID { get; set; }
    public string GroupName { get; set; }
    public bool Active { get; set; }
    public int OrderIndex { get; set; }
    public int ParentGroupID { get; set; }
}

将模型更改为@model IList<KTCEzone.Domain.Entities.EZone_ServiceGroup>,并从视图中删除@{var items = Model.ToArray();}并使用

@for (int i = 0; i < Model.Count; i++)
{
  <tr>
    <td>@Html.DisplayFor(m => m[i].GroupID)</td>
    <td>@Html.EditorFor(m=> m[i].GroupName)</td>
    <td>@Html.EditorFor(m=> m[i].ParentGroupID)</td>
    <td>@Html.CheckBoxFor(m=> m[i].Active) </td>
    <td>@Html.EditorFor(m=> m[i].OrderIndex) </td>
  </tr>
}

它将正确命名您的元素。如果无法将集合更改为IList,则需要为模型的类型使用自定义EditorTemplate,并与@Html.EditorFor() 一起使用

至于"我如何检查,以便只保存正在更改的行",所有控件都将被过账,因此您需要将过账的值与控制器中的原始值进行比较。

最新更新