MVC Viewmodel无法使用View访问模型

时间:2014-09-10 12:55:41

标签: asp.net-mvc asp.net-mvc-viewmodel

如何从我的视图中访问我的viewmodel?我的代码如下: - ,

我有两个模型(使用实体框架),它们的视图模型为: -

 public class ViewModelStory
{
    public IEnumerable<tbl_GCB_NewsItem> GCB_NewsItem { get; set; }
    public IEnumerable<tbl_GCB_ItemComment> comemnts { get; set; }

}

我的控制器通过以下方式填充模型: -

        ViewModelStory.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
                    where i.intItemIdentifier.ToString() == StoryId
                    select i).SingleOrDefault();

        ViewModelStory.comemnts = (from i in db.tbl_GCB_ItemComment
                                       where i.intItemIdentifier.ToString() == StoryId
                                       select i).ToList<tbl_GCB_ItemComment>();

我通过

返回模型
      return PartialView("NewsStory", ViewModelStory);

然后在我看来,我有以下声明

@model ViewModelStory
@using GCBSMVC.Models

要访问我的模型,我尝试了各种从Linq到并直接查询模型,但似乎没有任何工作: -     Html.DisplayFor(m =&gt; m.GCB_NewsItem ....     ViewModelStory.GCB_NewsItem.strItemCategory     Html.Raw(System.Web.HttpUtility.HtmlDecode(ViewModelStory.GCB_NewsItem.strItemHeadline))

1 个答案:

答案 0 :(得分:1)

您传递的是模型类的类型而不是实际的类。试试这个:

var model = new ViewModelStory();
model.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
                    where i.intItemIdentifier.ToString() == StoryId
                    select i).SingleOrDefault();

model.comemnts = (from i in db.tbl_GCB_ItemComment
                                       where i.intItemIdentifier.ToString() == StoryId
                                       select i).ToList<tbl_GCB_ItemComment>();

return PartialView("NewsStory", model);