在MVC 4中,submit将模型返回为null

时间:2014-11-17 20:21:39

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

我试图在提交时将部分视图中的数据发送到控制器,但它会以null发送。

这是视图的代码:

@model MvcApplication1.Models.mylist

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>custlist</title>
</head>
<body>
    @using (Ajax.BeginForm("Submit", "Home", new AjaxOptions() {
        UpdateTargetId = "custlist" })) 

    {
        <div>
            <p>
                @{Html.RenderPartial("el1", Model.Emplist);}
            </p>
            <p>
                @{Html.RenderPartial("clist", Model.Custlist);}
            </p>
        </div>
        <input type="submit" value="Submit" />
    }
</body>
</html>

控制器代码:

此方法用于调用传递模型的视图

public ActionResult custlist()
        {
            List<Employee> Emplist = new List<Employee>() {
            new Employee(){ ID = "1", Name = "A"},
            new Employee(){ ID = "2", Name = "B"},
            new Employee(){ ID = "3", Name = "C"},
            };
            List<Customer> CustList = new List<Customer>() {
            new Customer(){ CustID = "1", CustName = "X"},
            new Customer(){ CustID = "2", CustName = "Y"},
            new Customer(){ CustID = "3", CustName = "Z"},
            };
            mylist m = new mylist();
            m.Emplist = Emplist;
            m.Custlist = CustList;
            return View(m);
        }

下面的方法是在提交时被调用,但模型对象f被接收为null。

 [HttpPost]
    public ActionResult Submit(mylist f)
    {
        return View(f);
    }

1 个答案:

答案 0 :(得分:0)

只是一个简单的问题,你是否正在使用foreach进行循环?若是这样使用正常,请尝试使用此

  for(int index=0; index < Model.Emplist.Count; index++)
  {
   @Html.HiddenFor(m => Model.Emplist[index].ID)
   @Html.EditorFor(m => Model.Emplist[index].Name)
  }