【发布时间】:2015-08-28 12:20:26
【问题描述】:
我是 ASP.NET MVC 的新手,我只是好奇下一个场景的最佳实践是什么。我会将查询结果传递给视图:
public class HomeController : Controller
{
public ActionResult Index() // show last 3 posts from the database
{
DB db = new DB(); // DB is just a tiny wrapper to work with LocalDB sql database
db.openConnection(ConfigurationManager.ConnectionStrings["PostDBContext"].ConnectionString);
db.select(@"select p.id, p.title, p.content, FORMAT(p.created_at, 'yyyy-MM-dd') as created_at, u.firstname,
u.lastname, c.name
from posts p
inner join users u on (u.id = p.created_by)
inner join categories c on (c.id = p.category_id)
where p.visibility = 'public'
order by p.id desc limit 3");
while( db.read() > 0 ) // reads one row
{
....
}
db.closeConnection();
return View();
}
我已经阅读了几篇关于如何将数据从控制器传递到视图的文章。每篇文章都提到最好和推荐的方法是将数据从模型传递到视图或创建视图模型。所以使用这种方法意味着我需要创建一个 ViewModel 和一个 Model,如下所示:
public class FullPostViewModel
{
public List<FullPost> Posts { get; set; }
}
public class FullPost
{
public int id;
public string title;
public string content;
public string created_at;
public string author_firstname;
public string author_lastname;
public string category;
}
然后在控制器中:
....
FullPostViewModel model = new FullPostViewModel();
while( db.read() > 0 ) // reads one row
{
model.Posts.Add( new FullPost(){id = Convert.ToInt32(db[0]), title = db[1], ....});
}
...
return View(model);
或者最好是创建三个模型:Post、Category、User,然后 FullPost 包含这样的内容:
public class FullPost
{
public Post p;
public Category c;
public User u;
}
例如,如果您有更复杂的查询(3、4、... 连接),这意味着为每个表创建新类。当然,为每个表创建一个类是有意义的,因为这就是 ORM 的全部意义所在。
我只想知道使用模型/视图模型是否始终是显示查询结果的最佳实践(我知道 ViewBag 用于简单和小数据)?在 Laravel (PHP) 中,当涉及到连接的查询时,我经常不使用模型。它只是看起来更容易,但这并不意味着它可以。
【问题讨论】:
-
您不一定需要
FullPostViewModel模型。您可以将List<FullPost>传递给视图。 -
您的第一个代码示例不会向视图发送任何内容。所以我不确定这甚至说明了什么。任何类型都可以用作视图模型,包括查询的结果。当您想要将数据转换为特定于该视图的某些内容或包含特定于该视图的功能时,您需要创建一个自定义视图模型。如果视图只是绑定到后端类型,您可以将后端查询的结果发送给它。
-
@StephenMuecke 感谢您发布关于什么是 mvc 中的视图模型的帖子。
-
@David 我需要将查询结果存储到一些数据结构列表中,... SqlDataReader 用作无缓冲的数据流。必须关闭 SqlDataReader,现在最好在视图中写入逻辑 (SqlDataReader.Close())。至于第一个代码,我只是想展示我正在尝试做的事情(示例查询,......)。
标签: c# asp.net-mvc asp.net-mvc-5