【发布时间】:2014-10-12 12:17:33
【问题描述】:
我绝对是 ASP.NET MVC 的初学者。 这是我要为主(主页)页面做的事情:
- 获取最近 20 篇博文。
- 获取博客标签列表。
据我所知,在同一个视图中使用不同的模型是不可能的,所以我试图调用同一个存储库的不同方法,然后显示结果。但问题是 - 我不知道如何加入结果。 我应该创建新模型并传递给 View() 还是应该使用不同模型的局部视图? 这是控制器代码:
public ActionResult Index()
{
var top20 = PostRepository.GetLast20();
var tag = PostRepository.GetTags();
//How should I return to View() both top20 and tags?
return View();
}
附: ActionResult 索引包含错误的参数,所以我将其删除。 P.S.S.可能我应该展示我的存储库:
public class BlogPostRepository : IPostRepo, IDisposable
{
private BlogAspNet db;
public BlogPostRepository(BlogAspNet db)
{
this.db = db;
}
public IQueryable<blog_post> GetAll()
{
return db.blog_post.AsQueryable();
}
public IQueryable<tags> GetTags()
{
return db.tags.AsQueryable();
}
public IQueryable<ShortPostInfo> GetLast20()
{
var last = from a in db.blog_post
orderby a.Posted descending
select new ShortPostInfo
{
PostID = a.ID,
PostSubject = a.Subject,
PostAuthor = (from x in db.users where x.ID == a.Author select x.Login).FirstOrDefault(),
PostCreated = a.Posted,
PostImage = a.PostAvatar !=null ? a.PostAvatar : "other image",
PostRating = a.Rating != null ? a.Rating : 0,
PostedTags = (from x in db.posted_tags
join y in db.tags on x.TagID equals y.ID
where x.PostID == a.ID
select y.TagName).ToList()
};
return last.Take(20).AsQueryable();
}
这是界面:
public class ShortPostInfo
{
public int PostID { get; set; }
public string PostSubject { get; set; }
public DateTime? PostCreated { get; set; }
public string PostImage { get; set; }
public string PostAuthor { get; set; }
public byte? PostRating { get; set; }
public IList<string> PostedTags { get; set; }
}
public interface IPostRepo : IDisposable
{
IQueryable<blog_post> GetAll();
IQueryable<tags> GetTags();
IQueryable<ShortPostInfo> GetLast20();
IQueryable<ShortPostInfo> GetPostByTag(int tagid);
IQueryable<FullPostInfo> GetPostById(int id);
void Add(blog_post item);
void Update(blog_post item);
void Remove(int id);
}
【问题讨论】:
-
无论如何,您都应该创建新的 ViewModel,如果您返回数据库对象,那么您做错了。
标签: c# asp.net asp.net-mvc asp.net-mvc-4