public ActionResult listItems()
{
var getTopStories = DB.posts.Where(x => x.post_type == "blog").OrderByDescending(x => x.id).Take(4).ToList();
return View(getTopStories);
}
public ActionResult singleItem()
{
var single = DB.posts.Where(x => x.post_type == "paper").OrderByDescending(x => x.id).First();
return View(single);
}
作为我上面的代码,我有两个操作结果方法,但是都具有不同的条件,所以我想在不使用View Bag的情况下在View上显示这两个方法数据,我该怎么做?
答案 0 :(得分:0)
让我们假设您有一个带有某些属性(ID,名称等)的Post类。首先创建一个像这样的新类,
public class PostViewModel
{
public List<Post> PostList { get; set; }
public Post SinglePost { get; set; }
}
现在在您的操作结果中(不需要两个单独的操作结果)在这样的视图模型中映射数据
public ActionResult SingleAndlistPost()
{
PostViewModel model=new PostViewModel
{
PostList = DB.posts.Where(x => x.post_type == "blog").OrderByDescending(x => x.id).Take(4).ToList(),
SinglePost = DB.posts.Where(x => x.post_type == "paper").OrderByDescending(x => x.id).First()
};
return View(model);
}
最后在您的cshtml中查看这样的访问数据
@model YourProject.YourModel.PostViewModel
//.......
<p>@Model.SinglePost.MyProperty</p>
foreach (var list in Model.PostList)
{
<p>@list.MyProperty</p>
}