1

我试过这段代码,但我有这样的错误:

The model item passed into the dictionary is of type 
'System.Collections.Generic.List`1[XNet.Repository.Model.RoomType]', 
but this dictionary requires a model item of type 
'System.Collections.Generic.IEnumerable`1[XNet.Repository.Model.EditRoomTypeViewModel]'.

我不知道,什么部分给出错误。请帮忙。

我的服务

public List<EditRoomTypeViewModel> GetViewRoom(int RoomTypeID)

{
    List<RoomType> roomTypes = (from d in _RoomTypeRepository.All()
                          select d).ToList();

    List<EditRoomTypeViewModel> editRoomTypeViewModel = new List<EditRoomTypeViewModel>();

    foreach (RoomType roomType in roomTypes)
    {
        editRoomTypeViewModel.Add(new EditRoomTypeViewModel
        {
            RoomTypeID = RoomTypeID,
            RoomTypeName = roomType.RoomtypeName,
            RoomTypeDescription = roomType.RoomTypeDescripton,
        });
    }

    return editRoomTypeViewModel;
}

我的控制器

public ActionResult Room()
        {
            ViewBag.hotel = _hotelService.GetByID(2).HotelName;

            List<EditRoomTypeViewModel> editRoomTypeViewModel = _roomViewService.GetViewRoom(_HotelID);
            return View(editRoomTypeViewModel.FirstOrDefault());
        }

我的视图模型

 public class EditRoomTypeViewModel
    {
        public int RoomTypeID { get; set; }
        public string RoomTypeName { get; set; }
        public string RoomTypeDescription { get; set; }

    }

我的观点

@model IEnumerable<XNet.Repository.Model.EditRoomTypeViewModel>
@{
    ViewBag.Title = "Room";
}

<h2>Room</h2>
<div>
    @Html.Label("Hotel Name");
</div>

<div>
   @ViewBag.hotel
</div>

<table>
    @foreach (var a in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(model => a.RoomTypeName)
            </td>
            <td>
               <input style="width:100px;" type="button" title="EditRoomType" value="Edit"  onclick="location.href='@Url.Action("EditRoom", "Hotel", new { RoomTypeID = a.RoomTypeID})'" />
            </td>
        </tr>
    }
</table>

<input style="width:200px;" type="button" title="EditRoomType" value="New Room Type"  onclick="location.href='@Url.Action("NewRoom", "Hotel")    '" />
4

2 回答 2

0

只需删除控制器操作中的 .FirstOrDefault() 就可以了。

public ActionResult Room()
{
    ViewBag.hotel = _hotelService.GetByID(2).HotelName;

    List<EditRoomTypeViewModel> editRoomTypeViewModel = _roomViewService.GetViewRoom(_HotelID);
    return View(editRoomTypeViewModel);
}
于 2013-05-29T10:26:14.540 回答
0

我注意到您editRoomTypeViewModel在控制器中只返回了一个对象,但在您看来,您将模型声明为IEnumerable<XNet.Repository.Model.EditRoomTypeViewModel>.

另一点是错误似乎与ViewBag其他地方的分配有关,因为它包含this字典requires a model item of type并且可能唯一的类型dictionaryViewBag.

于 2013-05-29T06:50:27.227 回答