1

可能重复:
视图模型 IEnumerable<> 属性从 post 方法返回 null(未绑定)?

我遇到的问题与此处指定的问题几乎相同:

查看模型 IEnumerable<> 属性从 post 方法返回 null(未绑定)?

我的问题与上面链接的问题不同,在我的示例中,我正在程序上创建数据来填充我的视图模型。

但是,没有一个建议的解决方案可以为我解决这个问题。据我所知,我在下面显示的方法与 Travis J 的答案相同,但是我也尝试了为我的模型和/或“子模型”创建 EditorTemplate 的方法。我是 MVC 的新手,所以我很可能会做一些惊人的事情,显然是错误的。

这是一个简化的示例,显示了我的问题:

楷模:

public class Foo
{
  public string Bar { get; set; }

  public Foo(string bar)
  {
    Bar = bar;
  }

  public Foo(){}

}

public class Foos
{
  public List<Foo> ListOfFoos {get;set;}
}

控制器:

public ActionResult Index()
{
    Foos foos = new Foos
    {
      ListOfFoos = new List<Foo>()
    };
    // here I'm procedurally constructing some data to keep my example simple.
    for (int i = 0; i < 10; ++i)
    {
      foos.ListOfFoos.Add(new Foo(i.ToString()));
    }
    return View( foos );
}

[HttpPost]
public ActionResult Index(Foos foos)
{
  ??? foos.ListOfFoos is null here ???
  return View();
}

看法:

    @model OCC_Tracker.Models.Foos
    @using (Html.BeginForm())
    {

      <table>
      <tbody>
      @for (int i = 0; i < Model.ListOfFoos.Count; ++i)
      {

        <tr>
          <td>
            @Html.TextBoxFor(m => m.ListOfFoos[i].Bar)
          </td>
         </tr>
      }
      </tbody>
      </table>

    <button>Submit</button>
   }
4

0 回答 0