发布ViewModel后,使用多个列表对象检索ViewModel

时间:2018-12-02 14:47:37

标签: c# asp.net-mvc

我有一个像这样的viewmodel类:

public class ViewModel
{
    public string VendorService { get; set; }
    public List<ResponseView> responseList { get; set; }
}

控制器具有获取和发布编辑操作:

public ActionResult Edit(int? id)
{
    List<ResponseView> resp = getResponseView(id); //get the list of ResponseView objects.
    ViewModel view = new ViewModel();
    view.responseList = resp;
    view.VendorService = "Car Manufacturer";
    return View(view);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel view)
{
    if (ModelState.IsValid)
    {
        List<ResponseView> respList = new List<ResponseView>();
        respList = view.responseList;

        foreach(ResponseView resp in respList)
        {
            Debug.WriteLine(resp.Question);
        }

        return RedirectToAction("editConfirm");
    }

    return View("Index");
}

Edit.cshtml

@model Tools.Models.ViewModel
@{
  List<Tools.Models.ResponseView> respList= Model.responseList as List<Tools.Models.ResponseView;
}

        @foreach (var item in respList)
        {
           <div class="col-md-5">
                @Html.EditorFor(model => item.Response, "" } })
                @Html.ValidationMessageFor(model => item.Response, "", "" })
           </div>
         }

我能够根据需要显示视图和视图模型中的所有数据。但是,当我尝试在下面的foreach行上的post操作中检索响应时,得到的是空指针引用。

    List<ResponseView> respList = new List<ResponseView>();
    respList = view.responseList;

    foreach(ResponseView resp in respList)
    {
        Debug.WriteLine(resp.Response);
    }

1 个答案:

答案 0 :(得分:0)

您必须使用for代替foreach。请尝试这个,

@for (int i = 0; i < Model.responseList.Count; ++i) {
<div>
@Html.EditorFor(model => Model.responseList[i].Response, "")
</div>