How to Get CheckBox value

I am trying to get the checkbox value in controller action method but it gives me default false value in either case could you please tell that How can I get the actual checkbox value?

Index.cshtml

@model ORES.ViewModels.FormRightsViewModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            Form Role Rights Management
            <small>Role Rights Matrix</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
            <li><a href="#">Forms</a></li>
            <li class="active">General Elements</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">

            <!-- right column -->
            <div class="col-md-12">
                <!-- Horizontal Form -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">Form RoleRights</h3>
                    </div><!-- /.box-header -->
                    <!-- form start -->
                    @using (Html.BeginForm())
                    {
                        @Html.AntiForgeryToken()
                        <div class="form-horizontal">
                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="box-body">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Roles, htmlAttributes: new { @class = "col-sm-2 control-label" })
                                    <div class="col-sm-10">
                                        @Html.DropDownListFor(model => model.SelectRoleID, Model.Roles, "Select a Role", new { @class = "form-control" })
                                        @Html.ValidationMessageFor(model => model.SelectRoleID, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <table id="example2" class="table table-bordered table-hover">
                                    <thead>
                                        <tr>
                                            <th>@Html.DisplayName("Form ID")</th>
                                            <th>@Html.DisplayName("Form Name")</th>
                                            <th>@Html.DisplayName("Has Rights")</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var item in Model.Collection)
                                        {
                                            <tr>
                                                <td>@Html.DisplayFor(modelItem => item.FormID)</td>
                                                <td>@Html.DisplayFor(modelItem => item.FormName)</td>
                                                <td>@Html.CheckBoxFor(modelItem => item.HasRights)</td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div><!-- /.box-body -->
                            <div class="box-footer">
                                <button type="submit" class="btn btn-primary pull-right">Update RoleRight Matrix</button>
                            </div><!-- /.box-footer -->
                        </div>
                    }
                </div><!-- /.box -->

            </div><!--/.col (right) -->
        </div>   <!-- /.row -->
    </section><!-- /.content -->
</div>

Controller:

[HttpPost]
public ActionResult Index(ViewModels.FormRightsViewModel formRightMatrix)
{
    if (formRightMatrix != null && 
        formRightMatrix.Collection != null && 
        formRightMatrix.Collection.Count() > 0)
    {
        foreach (var item in formRightMatrix.Collection)
        {
            BusinessObjectLayer.RolesRightsManagement roleRights = new BusinessObjectLayer.RolesRightsManagement();
            BusinessLogicLayer.RoleRightsBLL roleRightsBLL = new BusinessLogicLayer.RoleRightsBLL();
            if (roleRightsBLL.CheckExistancebyFormIdAndRoleId(item.FormID, formRightMatrix.SelectRoleID,ref roleRights))
            {
                roleRights.IsView = item.HasRights;
                roleRights.ModifiedBy = BusinessLogicLayer.ORESHelper.GetCurrentUsername();
                roleRights.ModifiedOn = DateTime.Now;
                roleRightsBLL.Update(roleRights);
            }
            else
            {
                roleRights.FormId = item.FormID;
                roleRights.CreatedBy = BusinessLogicLayer.ORESHelper.GetCurrentUsername();
                roleRights.CreatedOn = DateTime.Now;
                roleRights.RoleId = formRightMatrix.SelectRoleID;
                roleRights.IsView = item.HasRights;
                roleRightsBLL.Create(roleRights);
            }

        }
        RedirectToAction("Index");
    }

    return View(formRightMatrix);
}

Model:

public class FormRightsViewModel
{
    BusinessLogicLayer.FormBLL formBll = new BusinessLogicLayer.FormBLL();

    [System.ComponentModel.DataAnnotations.Display(Name = "Roles:")]
    public System.Web.Mvc.SelectList Roles 
    { 
        get 
        { 
            return new System.Web.Mvc.SelectList(new BusinessLogicLayer.RoleBLL().GetAllRoles(), "ROLEID", "ROLE1"); 
        } 
    }

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage="Please Select Role!")]
    public int SelectRoleID { get; set; }

    private FormCollection _Collection;
    public FormCollection Collection 
    {
        get 
        {
            this._Collection = new FormCollection();

            IEnumerable<BusinessObjectLayer.Form> forms = formBll.GetAllForms();

            if (forms != null && forms.Count() > 0)
            {
                foreach (var form in forms)
                {
                    this._Collection.Add(new FormRoleRights { FormID = form.FormId, FormName = form.FormName });
                }
            }

            return this._Collection;
        }
    }

}

public class FormCollection : List<FormRoleRights>
{
    public FormCollection() 
        : base() 
    {
    }

    public FormCollection(int capacity)
        : base(capacity)
    { 
    }

    public FormCollection(IEnumerable<FormRoleRights> collection)
        : base(collection)
    { 
    }
}

public class FormRoleRights 
{
    [System.ComponentModel.DataAnnotations.Display(Name = "Form Name")]
    public string FormName { get; set; }

    [System.ComponentModel.DataAnnotations.Display(Name = "Form ID")]
    public int FormID { get; set; }

    [System.ComponentModel.DataAnnotations.Display(Name = "Has Rights")]
    public bool HasRights { get; set; }
}

Upvotes: 0

Views: 232

Answers (1)

monkeyhouse
monkeyhouse

Reputation: 2896

I think your ultimate issue - after all other corrections is that the Collection does not have a Set method ( on the FormRightsViewModel.Collection ). So each time you inspect or read it, you are resetting the values.

This is after you correct your model binding.

To correct the model binding, use the editor for approach. see way below for EditorFor model binding solutions.

I added the template

/Shared/EditorTemplates/FormRoleRights.cshtml

@model ViewModels.FormRoleRights

<tr>
   <td>@Html.DisplayFor(modelItem => Model.FormID)</td>
   <td>@Html.DisplayFor(modelItem => Model.FormName)</td>
   <td>@Html.CheckBoxFor(modelItem => Model.HasRights)</td>
   @Html.HiddenFor(model => Model.FormID)
</tr>

and use the EditorFor template in the table to ensure proper indexing during the rendnering

<table id="example2" class="table table-bordered table-hover">
<thead>
    <tr>
        <th>@Html.DisplayName("Form ID")</th>
        <th>@Html.DisplayName("Form Name")</th>
        <th>@Html.DisplayName("Has Rights")</th>
    </tr>
</thead>
<tbody>
    @Html.EditorFor(t => Model)
</tbody>
</table>

When I do, this the rendered html looks like

<form action="/Home/Index2" method="post"><input name="__RequestVerificationToken" type="hidden" value="CfDJ8IaY0wQy35JJvYSI6dpCxHJD6r_ijx_dc8VYTJzN1b95J0SMT7te3cR-H39qMhlrVQb82J8m0Z5D9SNbd6kf0O-X2yYrTuN01OAt4rxk9B8vM44_JwQUFjCWCZqI44gLSnuJnurApCRGQ_qcwa4LJZE">    <div class="form-horizontal">
        
        <div class="box-body">
            <div class="form-group">
                <label class="col-sm-2 control-label" for="Roles">Roles:</label>
                <div class="col-sm-10">
                    <select class="form-control" data-val="true" data-val-required="Please Select Role!" id="SelectRoleID" name="SelectRoleID"><option value="">Select a Role</option>
<option value="1">Write Role</option>
<option value="2">Read Role</option>
</select>
                    <span class="field-validation-valid text-danger" data-valmsg-for="SelectRoleID" data-valmsg-replace="true"></span>
                </div>
            </div>
            <table id="example2" class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>Form ID</th>
                        <th>Form Name</th>
                        <th>Has Rights</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
    <td>1</td>
    <td>A Test Form</td>
    <td><input data-val="true" data-val-required="The Has Rights field is required." id="Collection_0__HasRights" name="Collection[0].HasRights" type="checkbox" value="true"></td>
    <input data-val="true" data-val-required="The Form ID field is required." id="Collection_0__FormID" name="Collection[0].FormID" type="hidden" value="1">
</tr><tr>
    <td>2</td>
    <td>Another Test Form</td>
    <td><input data-val="true" data-val-required="The Has Rights field is required." id="Collection_1__HasRights" name="Collection[1].HasRights" type="checkbox" value="true"></td>
    <input data-val="true" data-val-required="The Form ID field is required." id="Collection_1__FormID" name="Collection[1].FormID" type="hidden" value="2">
</tr>
                </tbody>
            </table>
        </div><!-- /.box-body -->
        <div class="box-footer">
            <button type="submit" class="btn btn-primary pull-right">Update RoleRight Matrix</button>
        </div><!-- /.box-footer -->
    </div>
<input name="Collection[0].HasRights" type="hidden" value="false"><input name="Collection[1].HasRights" type="hidden" value="false"></form>

Notice the indexing on the FormID and HasRights Properties The name binding is like Collection[0].FormID

I then changed the post signature to make it easier to debug

Index (ViewModels.FormRightsViewModel formRightMatrix, FormRoleRights[] Collection)

The Collection property binds okay and shows the check box with the true and false values.


Simplify to pinpoint binding problems....

      public IActionResult Index3()
      {

        var form = new FormRoleRights()
        {
            FormID = 1,
            FormName = "A Test Form"
        };

        var form2 = new FormRoleRights()
        {
            FormID = 2,
            FormName = "Another Test Form"
        };


        var model = new FormCollection()
        {
            form, form2
        };

        return View(model);
    }

    [HttpPost]
    public IActionResult Index3(FormCollection fc)
    {           
        return Json(fc);
    }

Index3.cshtml

@model ViewModels.FormCollection

@{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm())
{

    <div class="box-body">       
    <table id="example2" class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>@Html.DisplayName("Form ID")</th>
                <th>@Html.DisplayName("Form Name")</th>
                <th>@Html.DisplayName("Has Rights")</th>
            </tr>
        </thead>
        <tbody>
            @Html.EditorFor(t => Model)
        </tbody>
    </table>
    </div><!-- /.box-body -->
    <div class="box-footer">
        <button type="submit" class="btn btn-primary pull-right">Update RoleRight Matrix</button>
    </div><!-- /.box-footer -->

}

/Shared/EditorTemplates/FormRoleRights.cshtml

@model ViewModels.FormRoleRights

<tr>
    <td>@Html.DisplayFor(modelItem => Model.FormID)</td>
    <td>@Html.DisplayFor(modelItem => Model.FormName)</td>
    <td>@Html.CheckBoxFor(modelItem => Model.HasRights)</td>
    @Html.HiddenFor(model => Model.FormID)
</tr>

Upvotes: 1

Related Questions