1

我正在尝试制作一个视图模型来显示复选框列表。当在数据库中找到其 ID 时,将选中一个复选框。但是,我的代码正在生成错误。

CheckFacilityVN

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace XNet.WebUI.Hotel.ViewModel
{
    public class CheckFacilityVM
    {
        public int FacilityID { get; set; }
        public string facilityName { get; set; }
        public List<FacilityAvailable> facilityAvailable { get; set; }
    }

    public class FacilityAvailable
    {
        public bool isCheck { get; set; }
    }
}

我的控制器

public ActionResult Facility()
        {
            var htl = _hotelService.ShowRoomFacility(2);
            var list = new List<FacilityAvailable>();
            foreach (var x in htl)
            {
                list.Add(new FacilityAvailable { FacilityID = htl.FacilityID, facilityName = htl.FacilityName, isCheck = htl.IsActive });
            }
            return View();
        }

我的构造函数

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

            return x;
        }

如何制作这些复选框?

4

1 回答 1

1

首先调整您的视图模型:

public class CheckFacilityVM
{
    public int FacilityID { get; set; }
    public string FacilityName { get; set; }
    public bool IsFacilityAvailable { get; set; }
}

然后使用这个视图模型:

public ActionResult Facility()
{
    var model = _hotelService
        .ShowRoomFacility(2)
        .Select(htl => new CheckFacilityVM
        {
            FacilityID = html.FacilityID,
            FacilityName = html.FacilityName,
            IsFacilityAvailable = htl.IsActive,
        })
        .ToList();

    return View(model);
}

然后写一个对应的视图:

@model List<CheckFacilityVM>

@using (Html.BeginForm())
{
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Is available</th>
            </tr>
        </thead>
        <tbody>
        @for (var 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].IsFacilityAvailable)
                </td>
            </tr>
        }
        </tbody>
    </table>

    <button type="submit">Save</button>
}

最后:

[HttpPost]
public ActionResult Facility(List<CheckFacilityVM> model)
{
    // process the values from the view model here ...
}
于 2013-05-23T09:02:02.503 回答