0

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

  • You cannot use a `foreach` loop to generate form controls for a collection (refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) and the model in your partial needs to be `@model WebOPMS.Models.AppRole` otherwise your inputs woul not have the correct `name` attributes. –  Apr 25 '16 at 09:23
  • i tried with 'for' loop also but did not work. from parent view i am passing the **Model** which is AppRole but it throws exception. – Shrivardhan BS Apr 25 '16 at 10:22
  • Then you did not do it right :) –  Apr 25 '16 at 10:23
  • yes i did not do it right and i have very little clue about this. I am mainly into Embedded development.. Wanted to learn MVC.. – Shrivardhan BS Apr 25 '16 at 10:25
  • any help in implementing this??? – Shrivardhan BS Apr 25 '16 at 10:33
  • You have posted far too much irrelevant code and no one is going to wade through it all (refer [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)) but [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) shows an example of how to implement it. –  Apr 25 '16 at 10:42
  • Thank you my friend.. i was able to make it work..... 1st mistake - `@model IEnumerable` was used in partial page, which i changed to `@model WebOPMS.Models.AppRole`. 2nd mistake i was using ICollection for one to many relation for which i cant implement the for loop.. now it is working... – Shrivardhan BS Apr 25 '16 at 10:46
  • Thank u very much... – Shrivardhan BS Apr 25 '16 at 10:50
  • Do **not** use a partial. Use an `EditorTemplate` as per the answer I linked to. –  Apr 25 '16 at 10:51
  • looks like not fully solved. `[HttpPost] public ActionResult RoleCreate(AppRole _role) ` gets the permission list also, i am able to see the data however, `if (ModelState.IsValid)` is failing. i have put following condition - `if (ModelState.IsValid) { database.AppRoles.Add(_role); database.SaveChanges(); return RedirectToAction("RoleIndex"); } else { var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception)); }` – Shrivardhan BS Apr 25 '16 at 11:02
  • errors doesn't give anything... no help from it... – Shrivardhan BS Apr 25 '16 at 11:03
  • I have no idea what code you have tried! –  Apr 25 '16 at 11:03
  • Thank U for the help this far.. will continue from here... – Shrivardhan BS Apr 25 '16 at 13:07

0 Answers0