在提交到ASP.NET mvc控制器

时间:2016-10-12 17:58:38

标签: asp.net-mvc

我有一个方法/控制器:

 public ActionResult Create([Bind(Include = "Id,Name")] RoleViewModel roleVM)

并且我在角色和权限之间存在多对多关系,并且需要将角色权限发布到该方法,因此我通过向绑定添加权限来更改方法:

 public ActionResult Create([Bind(Include = "Id,Name,Privileges")] RoleViewModel roleVM)

使用jstree控件显示角色权限,我拥有Javascript数组中的权限:

var arr = $('#tvPrivileges').jstree(false).get_checked();

        var filledArr = new Array();

        arr.forEach(fillPrivileges)
        { }

        function fillPrivileges(item, index) {

            var privilege = {
                Id: item,
                Name: ""
            }

            filledArr.push(privilege);
        }

角色和权限模型:

public class RoleViewModel
{
    public RoleViewModel()
    {
        this.Privileges = new List<PrivilegeViewModel>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public  List<PrivilegeViewModel> Privileges { get; set; }

}


public class PrivilegeViewModel
{

    public int Id { get; set; }

    public string Name { get; 

}

HTML:

@using (Html.BeginForm("Create", "RolesController", FormMethod.Post, new { id = "RoleForm" }))
            {
@Html.AntiForgeryToken()

<div class="form-horizontal">
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, Resources.Captions.Name, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
    </div>
<div class="form-group">
        @Html.LabelFor(model => model.Privileges, Resources.Captions.Privileges, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div id="tvPrivileges"></div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="@Resources.Captions.Create" class="btn btn-primary" />
            @Html.ActionLink(Resources.Captions.Cancel, "Index", null, new { @class = "btn btn-white"})
        </div>
    </div>
</div>

}

如何在提交表单之前为模型添加权限?

1 个答案:

答案 0 :(得分:0)

我添加了一个字符串属性PrivilegesRaw来保存权限:

public class RoleViewModel
{
    public RoleViewModel()
    {
        this.Privileges = new List<PrivilegeViewModel>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public  List<PrivilegeViewModel> Privileges { get; set; }

    public  string PrivilegesRaw { get; set; }

}

在视图中添加了这一行:

@Html.HiddenFor(m => m.PrivilegesRaw, new { @id = "hdnPrivileges" })

在提交之前填写隐藏字段内的权限:

    function BindPrivilegesToModel() {
    var arr = $('#tvPrivileges').jstree(false).get_checked();
    document.getElementById("hdnPrivileges").value = arr.join(',');
}

$(function () {
    $("#RoleForm").submit(function () { BindPrivilegesToModel(); });
})