如何在视图中查看视图模型的属性?

时间:2016-08-31 16:43:36

标签: c# asp.net-mvc razor

我需要在视图中访问视图模型的属性,因为我需要为剃刀中的某些内容赋值,但每次键入Model时。它没有显示让我接下来的属性错误。

这是我的代码:

@model PagedList.IPagedList<New_MinecraftNews_Webiste_MVC.Models.ArticlesViewModel>
@using PagedList.Mvc;
@{
    ViewBag.Title = Model.Images;
}

<h2>@Model.SelectedArticleType</h2>

@Model.SelectedArticleTypeViewBag.Title = Model.Images;错误。

错误是:

  

严重级代码描述项目文件行抑制状态   错误CS1061 IPagedList<ArticlesViewModel>不包含   “图像”的定义&#39;没有扩展方法&#39; Images&#39;接受一个   可以找到类型IPagedList<ArticlesViewModel>的第一个参数   (您是否缺少using指令或程序集引用?)

这是我的控制器:

[Route("Articles/{at}")]
public ActionResult ArticleTypes(string at, int page = 1, int pageSize = 15)
{

    articleViewModel.Images = new List<ImageInfo>();
    var modelList = (from a in db.Articles
                     where a.SelectedArticleType == at
                     orderby a.Id descending
                     select new ArticlesViewModel
                     {
                         Id = a.Id,
                         Body = a.Body,
                         Headline = a.Headline,
                         PostedDate = a.PostedDate,
                         SelectedArticleType = a.SelectedArticleType,
                         UserName = a.UserName
                     }).ToList();


    foreach (var item in modelList)
    {
       item.Images = imageService.GetImagesForArticle(item.Id);
    }

    PagedList<ArticlesViewModel> model = new PagedList<ArticlesViewModel>(modelList, page, pageSize);


    return View(model);
}

Viewmodel看起来像:

public class ArticlesViewModel
{
    public int Id { get; set; }

    public List<SelectListItem> ArticleType { get; set; }


    public string SelectedArticleType { get; set; }

    public string UserName { get; set; }
    [Required]
    public string Headline { get; set; }
    [Required]
    [DataType(DataType.MultilineText)]
    public string Body { get; set; }
    [DataType(DataType.Date)]
    public DateTime PostedDate { get; set; }

    public ImageInfo MainImage { get; set; }

    public List<ImageInfo> Images { get; set; }
}

2 个答案:

答案 0 :(得分:2)

@model PagedList.IPagedList<New_MinecraftNews_Webiste_MVC.Models.ArticlesViewModel>
@using PagedList.Mvc;
@{
    ViewBag.Title = "Page title goes here";
}

@foreach (var article in Model) {

    <h1>@article.Headline</h1>
    <h2>@article.SelectedArticleType</h2>

}

答案 1 :(得分:2)

Reference the PagedList object and not the interface

@model PagedList<New_MinecraftNews_Webiste_MVC.Models.ArticlesViewModel>
@using PagedList.Mvc;
@using PagedList;

PagedList is a list. So you have to access the child items

 @for (int i = 0; i < Model.Count(); i++)
 {
     @Html.DisplayFor(modelItem => Model[i].SelectedArticleType)

 }

If you need some 'header' type info on the page and a list associated with that header info, you will probably need to create a partial view for the list and pass the list in via a property on the header info class.

相关问题