5

关于这个有很多问题......但不知何故我无法让这个绑定工作,我仍然在我发布的视图模型中得到空值。这是 MVC 4。

这是主视图模型

public class RoleVM {

[Required]
[Display(Name = "Name of the Role")]
public string Role {get; set;}

public IEnumerable<RolePermission> permissions { get; set; }

}

这是 RolePermission 类

public class RolePermission {

public int id;

public bool permission_value;

public string name { get; set; } 

}

这是控制器中的 GET 创建方法

public ActionResult Create() {

        RoleVM role_vm = new RoleVM();

        var allpermissions = from p 
        in permission_repo.GetPermissions()
        select p; 

        role_vm.permissions = from p 
        in allpermissions 
        select new RolePermission
        { name = p.name, id = p.PermissionId, permission_value = false };

        return View(role_vm);
    }

这是 Create.cshtml 文件

@model RoleVM
@using (Html.BeginForm("Create", "Role", 
FormMethod.Post, new { @class = "permission_form" }))
{
@Html.ValidationSummary(true)

<fieldset>
    <legend>RoleVM</legend>

    <div class="form-item">
        @Html.LabelFor(model => model.Role)

        @Html.EditorFor(model => model.Role)
        @Html.ValidationMessageFor(model => model.Role)
    </div>

   @Html.EditorFor(model => model.permissions)

    <p>
        <input class="submit-btn" type="submit" value="Create" />
    </p>
</fieldset>
}

接下来是位于 ~/Views/Shared/EditorTemplates 中的 rolepermissions.cshtml 文件

@model RolePermission

<div class="form-item">
      @Html.HiddenFor(modelItem => modelItem.id) 
      @Html.LabelFor(modelItem => modelItem.permission_value, Model.name)
      @Html.CheckBoxFor(modelItem => modelItem.permission_value) 
</div>

这是在页面上呈现的其中一个 html 项的示例

<div class="form-item">

      <input data-val="true" data-val-number="The field Int32 must be a number." data-val-required="The Int32 field is required." id="permissions_2__id" name="permissions[2].id" type="hidden" value="3" /> 

      <label for="permissions_2__permission_value">Role-Edit</label>
      <input data-val="true" data-val-required="The Boolean field is required."  id="permissions_2__permission_value" name="permissions[2].permission_value"
 type="checkbox" value="true" /><input name="permissions[2].permission_value"  type="hidden" value="false" /> 

</div>

最后是 Create POST 方法

    [HttpPost]
    public ActionResult Create(RoleVM rolevm)
    {

        //In here rolevm.role is populated based on the textbox input
        //However rolevm.permissions is there with the correct 
        //number of items, but the values all are not binded
        // id is null, name is empty, and permission_value is false 
        // regardless of which checkboxes were checked 


        return RedirectToAction("Index");
    }

对发布模型的绑定问题的任何帮助都会非常棒。

4

1 回答 1

11

这是一个简单的问题,如果其他人遇到它,也许这会对他们有所帮助。我没有使用 get 声明为属性的类的属性;放;

public class RolePermission {

public int id { get; set; } 

public bool permission_value { get; set; } 

public string name { get; set; } 

}
于 2012-07-18T22:37:21.563 回答