lundi 25 avril 2016

Get checkbox value placed in partial view table

I am very much new to MVC convept. I have two model class with 1 to many relation. find below the code.

Role:

public partial class AppRole
{
    public AppRole()
    {
        AppPermissions = new HashSet<AppPermission>();
        AppUsers = new HashSet<AppUser>();
    }

    public int AppRoleId { get; set; }

    [Required]
    public string RoleName { get; set; }
    public string RoleDescription { get; set; }
    public bool IsSysAdmin { get; set; }
    public virtual ICollection<AppPermission> AppPermissions 
    { get; set;  }
    public virtual ICollection<AppUser> AppUsers { get; set; } 
}

Permission:

public partial class AppPermission
{
    public AppPermission()
    {
    }

    public int AppPermissionId { get; set; }

    [Required]
    public string Name { get; set; }

    public bool Enable { get; set; }

    [Required]
    [StringLength(50)]
    public string PermissionDescription { get; set; }

    public Guid AppRoleId { get; set; } 
    public AppRole AppRole { get; set; }
}

AppPermission is used to set the access permission to different modules. For Eg: 1. User 2. Role 3. Products 4. Customer

Permission is created for every module using checkbox Enable rendered in the table.

When RoleCreate view is rendered, i want permission to be part of the view as a table and the rows are added during runtime which is saved to database when role is saved.

I am able to get the RoleCreate working and get the permisions using partial view. However, i am not able to get the permissions table checkbox data when role is saved.

Find below RoleCreate and ParmissionPartialView code.

RoleCreate:

@model WebOPMS.Models.AppRole
@{
    ViewBag.Title = "Create Role";
}
<script type="text/javascript">
    $(document).ready(function () {
        $(":input[type='submit']").button();
        $(":input[type='button']").button();
     })
</script>
<div class="panel">
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <div class="form-horizontal">
        <h3>
            Create Role
        </h3>

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(m => m.RoleName, new { @class = "col-md-2  control-label" })
            <div class="col-md-3">
                @Html.TextBoxFor(m => m.RoleName, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.RoleName, "", new {   @class = "text-danger" })
            </div>

            @Html.LabelFor(m => m.IsSysAdmin, new { @class = "col-md-2 control-label" })
            <div class="col-md-1">
                @Html.CheckBoxFor(m => m.IsSysAdmin, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.IsSysAdmin, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.RoleDescription, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextAreaFor(m => m.RoleDescription, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.RoleDescription,   "",                     new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn     btn-default" />
            </div>
        </div>
    </div>

    <h4>
        List of Permissions
    </h4>
    @*@Html.Partial("PermissionPartialView", Model)*@
    @Html.Partial("PermissionPartialView", Model.AppPermissions)

}
</div>


<div>
    @Html.ActionLink("Go to Roles", "RoleIndex", "Admin")
</div> 

PermissionPartialView:

    @model IEnumerable<WebOPMS.Models.AppPermission>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
    <th>
        Name
    </th>
    <th>
        Enable
    </th>
    <th>
        PermissionDescription
    </th>
    <th>
        @Html.DisplayNameFor(model => model.AppRoleId)
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.CheckBoxFor(modelItem => item.Enable)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PermissionDescription)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.AppRoleId)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.AppPermissionId     }) |
        @Html.ActionLink("Details", "Details", new { id=item.AppPermissionId }) |
        @Html.ActionLink("Delete", "Delete", new {     id=item.AppPermissionId })
    </td>
</tr>
}

</table>

Find below code of RoleCreate Action in the controller:

public ActionResult RoleCreate()
    {
        AppRole _approle = new AppRole(); 
        AppUser user = database.AppUsers.Where(r => r.Username ==  User.Identity.Name).FirstOrDefault();
        ViewBag.List_boolNullYesNo = this.List_boolNullYesNo();

        Assembly asm =  Assembly.GetAssembly(typeof(WebOPMS.MvcApplication));

        var controlleractionlist = asm.GetTypes()
                .Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
                .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
                .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
                .Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
                .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();

        List<AppPermission> perList = new List<AppPermission>();

        var list = new List<RolePermissionEditorViewModel>();

        foreach (var st in controlleractionlist)
        {
            if ((perList.Any(item => item.Name == string.Format("{0}-{1}",
                GetSplitString(st.Controller, "Controller"), st.Action))) == false)
            {
                AppPermission per = new AppPermission();
                RolePermissionEditorViewModel newMdl = new RolePermissionEditorViewModel();
                newMdl.Name = string.Format("{0}-{1}", GetSplitString(st.Controller, "Controller"), st.Action);
                newMdl.IsEnable = true;
                list.Add(newMdl);

                per.Name = string.Format("{0}-{1}", GetSplitString(st.Controller, "Controller"), st.Action);
                per.Enable = true;
                _approle.AppPermissions.Add(per);
                perList.Add(per);
            }
        }

        var outObj = list.Select(row => new SelectListItem()
        {
            Text = row.Name,
            Value = row.PermissionId.ToString(),
            Selected = row.IsEnable
        });

        ViewBag.keydata = outObj;

        ViewData["pers"] = perList;
        return View(_approle);
    }

I want permission table to be populate in runtime with chebox and when submit is pressed both role create and permission screen to be saved to database.

Please help me with this so that i can progress in this personal project.

Regards,

Shri

Aucun commentaire:

Enregistrer un commentaire