如何使用视图模型选中复选框

时间:2013-05-24 06:26:38

标签: asp.net-mvc-4

我尝试制作一个简单的项目,检查复选框列表。我的数据库是这样的......!enter image description here

我希望在酒店有设施时查看我的复选框...

我有这样的代码......

我的控制器

public ActionResult Facility()
        {
            var model = db.Facilities
                        .Where (htl => htl.FacilityID == hotelFacility.FacilityID)
                        .Select(htl => new CheckFacilityVM
                        {
                            FacilityID = htl.FacilityID,
                            facilityName = htl.FacilityName,
                            facilityAvailable = htl.IsActive == true,
                        })
                        .ToList();



            return View(model);
        }

我的建筑师课程

 public Facility ShowRoomFacility(int HotelID)
        {
            var x = (from d in db.Facilities
                     where d.FacilityID == HotelID
                     select d).FirstOrDefault();

            return x;
        }

我的观点

@model List<XNet.WebUI.Hotel.ViewModel.CheckFacilityVM>

@{
    ViewBag.Title = "Facility";
}

<h2>Facility</h2>

@using (Html.BeginForm())
{
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th> is available</th>
            </tr>
        </thead>
        <tbody>
            @for (int i = 0; i < Model.Count; i++)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(x => x[i].FacilityID)
                        @Html.HiddenFor(x => x[i].FacilityID)
                    </td>
                    <td>
                        @Html.DisplayFor(x => x[i].facilityName)
                        @Html.HiddenFor(x => x[i].facilityName)
                    </td>
                    <td>
                        @Html.CheckBoxFor(x => x[i].facilityAvailable)
                    </td>
                </tr>
            }
        </tbody>
    </table>       
}

    <br />
    <input style="width:100px;" type="button" title="Save" value="Save" onclick="location.href='@Url.Action("Index","Hotel")'" />
    <input style="width:100px;" type="button" title="Reset" value="Reset" onclick="location.href='@Url.Action("Facility","Hotel")'" />
    <input style="width:100px;" type="button" title="Cancel" value="Cancel"  onclick="location.href='@Url.Action("Room","Hotel")'" />

如何勾选复选框? 请帮帮我

1 个答案:

答案 0 :(得分:1)

您希望将数据库中的true / false存储为一个位。 0为假,1为真。

然后,当您的视图模型中有一个布尔属性时,由数据库填充

public bool FacilityXAvailable { get; set; }

在您的视图中,您可以执行此操作

@Html.DisplayFor(model=>model.FacilityXAvailable)

根据Db值显示未选中的复选框。