Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - How to use @Html.CheckBoxFor() while dealing with a List<ViewModel>

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...