在视图中显示来自viewmodel的数据

时间:2013-05-29 06:33:27

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor

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

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")    '" />

2 个答案:

答案 0 :(得分:0)

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

另一点是该错误似乎与ViewBag在其他地方的分配有关,因为它包含this 词典 {{ 1}}和probablt类型requires a model item of type的唯一内容是dictionary

答案 1 :(得分:0)

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

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

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