ViewModel使用Ajax更新,Model不绑定

时间:2015-11-09 15:47:21

标签: c# asp.net ajax asp.net-mvc partial-views

我有组织作为客户。每个组织下都有几个用户。在视图中,从下拉列表中选择组织时,使用Ajax从数据库更新该特定组织下的用户。当我发布模型时,用户列表为空。我尝试了几种选择,但似乎没有任何效果。这是我最终代码的简化版本。

public class AccessModel
{
    public List<Organization> AllOrganizations { get; set; }
    public List<UserModel> Users { get; set; }
    //and several other properties 
}

我的行动

[HttpGet]
public ActionResult GrantAccess()
         {
             var model = new AccessModel();
             model.AllOrganizations = db.Organizations.ToList(); 
             return View(model);   
         }

我的观点

@model MyModels.AccessModel
 @using (Html.BeginForm("GrantAccess", "Access", FormMethod.Post))
 {
 <div>
   @Html.DropDownList("Organizations", new SelectList(Model.AllOrganizations, "Id", "Name"),
       "choose", new { htmlAttributes = new { @onchange = "getUsers(this.value)" })
  </div>
<div id="Users">
   @{Html.RenderPartial("_UsersList", Model.Users);}
</div>
 }

我的Jquery

<script>
    function getUsers(str) {
        $("#Users").load('@(Url.Action("ReturnUsers", "Product", null))?orgNumber=' + str);            
    }
</script>

从Ajax调用时呈现部分页面的My Action

public ActionResult ReturnUsers(int orgNumber)
         {
             var usersList= db.Users.Where(u => u.OrganizationId == orgNumber).ToList();
             var model= new AccessModel();
             model.Users = usersList; 
             return PartialView("_UsersList", model); 
         }

部分页面_UsersList.cshtml

@model AccessModel

@if (Model.Users != null)
{
    foreach (var item in Model.Users)
    {  
    <fieldset>
        @Html.HiddenFor(modelItem => item.User.Id)
        @Html.CheckBoxFor(modelItem => item.isSelected)
        @Html.DisplayFor(modelItem => item.User.LastName)
        @Html.DisplayFor(modelItem => item.User.FirstName)
    </fieldset>
    }
}

最后,The Post Action

[HttpPost]
public ActionResult GrantAccess(AccessModel model)
         {           
            //here model.Users is null!
         }

视图显示用户正常,只有值不会传递给我的Post Model。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

如果使用for循环而不是foreach,则name属性将以模型绑定器可以拾取的格式呈现。

@model AccessModel

@if (Model.Users != null)
{
    @for (var i = 0; i < Model.Users.Count; i++)
    {  
    <fieldset>
        @Html.HiddenFor(modelItem => Model.Users[i].Id)
        @Html.CheckBoxFor(modelItem => Model.Users[i].isSelected)
        @Html.DisplayFor(modelItem => Model.Users[i].LastName)
        @Html.DisplayFor(modelItem => Model.Users[i].FirstName)
    </fieldset>
    }
}