7

This is my View. How to use CheckboxFor():

@using eMCViewModels;
@model eMCViewModels.RolesViewModel
@{
    ViewBag.Title = "CreateNew";
}
<h2>
    CreateNew<
/h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>RolesViewModel</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div>
            @foreach (RoleAccessViewModel mnu in Model.RoleAccess)
            {
                 // How to use checkboxfor here?
            }
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Model.RoleAccess is a List<RoleAccessViewModel> and I want to create checkbox using @Html.CheckBoxFor().

This is my RoleAccessViewModel

public class RoleAccessViewModel
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }
    public int MenuID { get; set; }
    public string MenuDisplayName { get; set; }
    public string MenuDiscription { get; set; }
    public string IsEnabled { get; set; } // changed to bool
}

Suppose I have 5 items in list, then I need 5 checkbox with ID=menuID and Text = menuDisplayName. How can I achieve this?

EDIT

My attempt

@Html.CheckBoxFor(x=>x.RoleAccess.SingleOrDefault(r=>r.MenuID==mnu.MenuID).IsEnabled )
@Html.LabelFor(x=>x.RoleAccess.SingleOrDefault(r=>r.MenuID==mnu.MenuID ).MenuDisplayName ) 

But after changing the type of IsEnabled from string to bool. The checkbox works. But Label prints only MenuDisplayName instead of values . Can any one helps ?

4
  • What have you tried when trying to call CheckBoxFor? I don't see an attempt to actually call it. Commented Jul 25, 2012 at 15:05
  • @casperOne, that's the whole point of the question. Apparently the OP doesn't know that the CheckBoxFor helper operates only on boolean fields, that's why you are not seeing any attempts, because his view model simply is not adapted to work with check boxes. Commented Jul 25, 2012 at 15:13
  • I'm not sure why your trying to use int for a Boolean value. If this is a True/False item, then you'll want to set it accordingly. How would you evaluate a true/false from a numerical value? The second issue will be when you post back a collection to the controller - given your code. See haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx for you next issue.... Commented Jul 25, 2012 at 15:23
  • @casperOne I have tried a lot and getting compile time issue. That is because the type of IsEnabled is string. It works when i changed to bool. Please see the updated question Commented Jul 25, 2012 at 15:35

4 Answers 4

23

If I undestood right, You mean this? And IsEnabled should bool type

model

public class RoleAccessViewModel
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }
    public int MenuID { get; set; }
    public string MenuDisplayName { get; set; }
    public string MenuDiscription { get; set; }
    public bool IsEnabled { get; set; }
}

view

@foreach (RoleAccessViewModel mnu in Model.RoleAccess)
{
    @Html.CheckBoxFor(m => mnu.IsEnabled )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why isn't this flagged as the best answer?
12

Change foreach with for

@for(int i = 0; i < Model.RoleAccess.Count; i++)
{
    Html.CheckBoxFor(Model.RoleAccess[i].IsEnabled, new { id = Model.RoleAccess[i].MenuID });
    Html.DisplayFor(Model.RoleAccess[i].MenuDisplayName); // or just Model.RoleAccess[i].MenuDisplayName
}

6 Comments

This won't work since the user is trying to convert an int to bool
Well, I think he can do it himself if this approach works for him
@Madman ` Html.LabelFor(Model.RoleAccess[i].MenuDisplayName);` this will print only MenuDisplayName. Why ? It is expected to print the values right ?
@VeeKeyBee this my misprint. I meant DisplayFor.
@Madman I m sorry. I am new to MVC. So I thought Label will prints something <label>Data</label>. Thanks :)
|
9

CheckBoxFor works with boolean properties only. So the first thing you need to do is to modify your view model in order to include a boolean property indicating whether the record was selected:

public class RoleAccessViewModel
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }
    public int MenuID { get; set; }
    public string MenuDisplayName { get; set; }
    public string MenuDiscription { get; set; }
    public bool IsEnabled { get; set; }
}

and then I would recommend replacing your foreach loop with an editor template:

<div>
    @Html.EditorFor(x => x.RoleAccess)
</div>

and finally write the corresponding editor template which will automatically be rendered for each element of the RolesAccess collection (~/Views/Shared/EditorTemplates/RoleAccessViewModel.cshtml):

@model RoleAccessViewModel
@Html.HiddenFor(x => x.RoleID)
... might want to include additional hidden fields
... for the other properties that you want to be bound back

@Html.LabelFor(x => x.IsEnabled, Model.RoleName)
@Html.CheckBoxFor(x => x.IsEnabled)

3 Comments

Thanks a lot for your help. I m new to MVC. May I know why I need to avoid using for loop ?
Many reasons: it's ugly and within the foreach loop you will generate incorrect names for your input fields and the default model binder won't be able to deserialize the values back when you submit the form. Why not stick with the conventions that are built directly into the framework. Makes your views so much simpler and correct.
Thanks. Let me try to find more advantages and will check the way u mentioned.
0

I know it is pretty old but

In your model use DataAnotations Display Attribute

public class MyModel
   int ID{get; set;};
   [Display(Name = "Last Name")]
   string LastName {get; set;};
end class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.