ASP.Net MVC - 更改下拉列表后无法设置@ Html.Checkbox的值

时间:2015-01-16 18:14:34

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

我一直在寻找类似的东西,什么都找不到...... 我正在使用ASP.NET MVC 4.我正在构建一个页面,以便我的应用程序中的用户可以管理与每个角色关联的权限。 所以我有一个@htmlDropDownList的视图来显示所有可用的角色,下面是一个@ Html.CheckBox,用于上面选择的每个角色的权限。

第一次呈现视图时,根据该角色的许可,复选框都设置为true或false。一切都很好,生活很好:)。当drop的值改变时,我使用$ .ajax发布SelectedRoleId。然后,我获取新选定角色的所有权限。 在调试中,在剃刀视图中,我可以确认模型中的新值(true或false)是否正确。问题是复选框在角色更改之前显示旧值。 这是我提出的第一个问题,所以如果问题没有得到最好的解决,我将不得不道歉。 并提前告诉大家:)

所以这是我的控制器:

       public ActionResult Index(int ? SelectedRoleId)
    {

        ManagePermissionsViewModel model = new ManagePermissionsViewModel();

        if (SelectedRoleId == null)
        {
            model.SelectedRoleID = 1; // value 1 is the supervisor Role
        }
        else
        {
            model.SelectedRoleID = SelectedRoleId;
        }
        //values for the dropdownlist of Roles 
        var items = from x in db.UserRoles
                    select x;
        model.RoleList = new SelectList(items, "Id", "DESCRIPTION");

        //gets all the permissions of the selected role 
        model.EntirePermissionList = (from k in db.Permissions
                                      select new Permission
                                      {
                                          IdPermission = k.Id,
                                          PermissionDescription = k.Description,
                                          IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
                                          PermissionGroupId = (int)k.PermissionGroupId
                                      }).ToList();
        //Gets all the groups of Permissions
        model.ListPermissionGroups = (from l in db.PermissionGroups
                                      select new PermissionGroup
                                      {
                                          Id = l.Id,
                                          Description = l.Description
                                      }).ToList();
         return View(model);
    }
             [HttpPost]
    public ActionResult Index(FormCollection form) {

        switch (form["SubmitButton"])
        {
            case "Save":
                SavePermissions();
                break;
            default:
                return RedirectToAction("Index", new RouteValueDictionary(new { controller = "ManagePermissions", action = "Index", SelectedRoleId = Convert.ToInt32(form["SelectedRoleId"]) }));
           }

        return View();

    }

这是我的观点:

    '@model AML.Web.Models.ManagePermissionsViewModel
     @using (Html.BeginForm("Index", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
  {

@Html.Label("Role :", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("RoleId", Model.RoleList, new { id = "RoleId" })

<div>

    @foreach (var item in Model.ListPermissionGroups)
    {
        <h3> @item.Description</h3>

       foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
        {

            <h5>
                @permission.PermissionDescription
                @Html.CheckBox("Chk_Permisssion", permission.IsSet)

            </h5>

        }
    }

</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
    }
  @section Scripts {
<script type="text/JavaScript">
    $(document).ready(function () {

        $("#RoleId").change(function (e) {
            e.preventDefault();
            $.ajax({
                url: "/ManagePermissions/Index",
                cache: false,
                type: "POST",
                data: { 'SelectedRoleId': $(this).val() },
                dataType: "json",
                success: function (result) { console.log("Sucess!"); },
                error: function (error) { console.log("Error!"); }
            })
        });
    });

</script>

}

我的viewModel:

    public class ManagePermissionsViewModel
{

    public int? SelectedRoleID { get; set; }
    public string SelectedRoleDescription { get; set; }
    public SelectList RoleList { get; set; }
    public List<Permission> EntirePermissionList { get; set; }
    public List<PermissionGroup> ListPermissionGroups { get; set; }
}

public class Permission
{

    public int IdPermission { get; set; }
    public bool IsSet { get; set; }
    public string PermissionDescription { get; set; }
    public int PermissionGroupId { get; set; }
}
public class PermissionGroup {

    public int Id { get; set; }
    public string Description{ get; set; }

}

更新1 - 好吧,我想我明白了。让我发布我的方法

在视图中:

      @Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList,null,
    new { onchange = "document.location.href = '/ManagePermissions/Index?SelectedRoleId=' + this.options[this.selectedIndex].value;" })
    <div>

        @foreach (var item in Model.ListPermissionGroups)
        {
            <h3> @item.Description</h3>



            foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
            {

                <h5>

                    @permission.PermissionDescription
                    <input type="checkbox" id="@permission.IdPermission" checked="@permission.IsSet">
                </h5>

            }
        }

    </div>

在控制器中:

    public ActionResult Index(int? SelectedRoleId)
    {

        ManagePermissionsViewModel model = new ManagePermissionsViewModel();
        ModelState.Clear();
        if (SelectedRoleId == null)
        {
            model.SelectedRoleID = 1;
        }
        else
        {
            model.SelectedRoleID = SelectedRoleId;
        }

        var items = from x in db.UserRoles
                    select x;
        model.RoleList = new SelectList(items, "Id", "DESCRIPTION");

        model.EntirePermissionList = (from k in db.Permissions
                                      select new Permission
                                      {
                                          IdPermission = k.Id,
                                          PermissionDescription = k.Description,
                                          IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
                                          PermissionGroupId = (int)k.PermissionGroupId
                                      }).ToList();

        model.ListPermissionGroups = (from l in db.PermissionGroups
                                      select new PermissionGroup
                                      {
                                          Id = l.Id,
                                          Description = l.Description
                                      }).ToList();
        ModelState.Clear();
        return View(model);
    }

现在每次Drop更改值时,复选框中的权限都会更新。我得到它来处理drop上的属性,&#34; on change = Document.location.hef = URL&#34;。这是一个好方法吗?或者我应该使用类似ajax请求的东西?

更新2

控制器:

        public async Task<ActionResult> Index(int? SelectedRoleId)
    {
        if (SelectedRoleId == null)
        {
            SelectedRoleId = 1;
        }

        var model = await GetSelectedPermissions(SelectedRoleId);
        return this.View("Index",model);

    }


    [HttpGet]
    public async Task<ActionResult> GetPermissions(string Id)
    {


        var SelectedRoleId = int.Parse(Id);
        var model = await this.GetSelectedPermissions(SelectedRoleId);
        return PartialView("_ManagePermissions", model);
    }

    private async Task<ManagePermissionsViewModel> GetSelectedPermissions(int? SelectedRoleId)  
    {

        ModelState.Clear();
        ManagePermissionsViewModel model = new ManagePermissionsViewModel();
        model.SelectedRoleID = SelectedRoleId;

        var items = from x in db.UserRoles
                    select x;
        model.RoleList = new SelectList(items, "Id", "DESCRIPTION");

        model.EntirePermissionList = await (from k in db.Permissions
                                      select new Permission
                                      {
                                          IdPermission = k.Id,
                                          PermissionDescription = k.Description,
                                          IsSet = db.RolePermissions.Any(n => n.RoleId == model.SelectedRoleID && n.PermissionId == k.Id),
                                          PermissionGroupId = (int)k.PermissionGroupId
                                      }).ToListAsync();

        model.ListPermissionGroups = await (from l in db.PermissionGroups
                                      select new PermissionGroup
                                      {
                                          Id = l.Id,
                                          Description = l.Description
                                      }).ToListAsync();

        return model;
    }

视图

     <h2>Permissions - Ajax with Partial View</h2>
     @using (Html.BeginForm("SaveData", "ManagePermissions", FormMethod.Post, new { id = "MyForm" }))
    {

@Html.Label("Role :", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(n => n.SelectedRoleID, Model.RoleList, null, null)
<div id="target">
    @Html.Partial("~/Views/Shared/_ManagePermissions.cshtml", Model)
</div>
<input type="submit" value="Save" name="SubmitButton" class="btn btn-default" />
      }
      @section Scripts {

<script type="text/javascript">
    $(document).ready(function () {
        $("#SelectedRoleID").change(function () {
            var SelectedRoleID = $("#SelectedRoleID").val();
            $("#target").load('@(Url.Action("GetPermissions","ManagePermissions",null, Request.Url.Scheme))?Id=' + SelectedRoleID);
        });
    });
</script>

           }

部分视图:

    <div>

@foreach (var item in Model.ListPermissionGroups)
{
    <h3> @item.Description</h3>
    foreach (var permission in Model.EntirePermissionList.Where(n => n.PermissionGroupId == item.Id))
    {
        <h5>
            @permission.PermissionDescription
            <input type="checkbox" id="@permission.IdPermission" checked="@permission.IsSet">
        </h5>

    }
}
    </div>

0 个答案:

没有答案