I'm new to ASP.NET MVC and just curious what is the best practise for next scenario. I would to pass query result to a view:
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();
}
I've read several articles about how to pass data from controller to a view. Every article mentions that the best and recommended way is to pass data from Model to View or create ViewModels. So using this approach means that I need to create a ViewModel and a Model, something like this:
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;
}
And then in controller:
....
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);
Or is it better to make three Models: Post, Category, User and then the FullPost contains something like this:
public class FullPost
{
public Post p;
public Category c;
public User u;
}
If you have for example even more complex query (3, 4, ... joins), this would mean to create new class for each table. Well of course it makes sense to create one class for each table, because this is what ORM is all about.
I just want to know if is using Models/ViewModels always a best practise for showing query results (I'm aware of ViewBag for simple and small data)? In Laravel (PHP) I often didn't use Models when it came to queries which involved joins. It just seemed easier which doesn't mean its ok.