I have a query where I need to get post + every tag that it has. But since Tags are in separate table it makes things hard for me for two reasons. I am not really sure that I even need to pass two values, maybe I can do this somehow differently.
Note that Model is created automatically using LINQ to SQL Classes.
DB

Code
public ActionResult Edit(int id)
{
// Get post from DB
var post = (from p in _db.Posts
where p.ID == id
select p).Single();
// Get PostTags from DB
var postTag = (from pt in _db.PostTags
where pt.PostID == id
select pt);
// Now looping through PostTags in order to find all tag names associated with the post
string tagList = string.Empty;
foreach (var pt in postTag)
{
var tag = (from t in _db.Tags
where t.ID == pt.TagID
select t).Single();
tagList += tag.Name + " ";
}
return Content(tagList); // This works as intended, outputs all tags for current post
return View(); // How can I return post itself + tagList ?
}
Problem
-
As you can see I want to pass
postto my view and it makes sense, but I need to somehow pass thetagListstring that contains tags as well. How can I do that? -
I think my query is bad. I’m not experienced with SQL/LINQ so this is the only thing that I came up with. Maybe I can do the same thing somewhat "smarter"?
Okey, thank you for answers. Both ViewBag and creating BlogViewModel are good. I will go with BlogViewModel I think. But my second question still remains.
Have you considered creating a ViewModel that would hold both of these objects, and passing that ViewModel to your View? You can also use LINQ to improve your queries.
(Note : I’m posting this from my phone so the syntax could be off)
Model:
Code (using LINQ):
You could also use other methods to send the message across, such as storing them in the ViewData if you didn’t want to implement a Model for it.