Reputation: 535
I've googled about but still haven't found what I'm looking for. What I want to happen is to get all the comments for a particular image that's been posted.
@model IEnumerable<Project1.Models.Picture>
@{
Layout = "~/Views/Shared/_PictureLayout.cshtml";
ViewBag.Title = "Animal Pictures";
}
@foreach (var picture in Model)
{
long id = picture.PictureID;
<div class="picture">
@Html.ActionLink("Picture", "IndexPic", "Pictures", new { id = picture.PictureID
}, true)
<img src="" alt="@picture.File" />
Posted by @Html.ActionLink(picture.GetUsername(picture.UserID), "Index",
"Pictures", new { username = picture.GetUsername(picture.UserID) }, true)
at @picture.Posted
@picture.GetComments(picture.PictureID) **** HERE LIES THE PROBLEM!!!
</div>
}
The error that is returned is Cannot implicitly convert type 'void' to 'object'
The plan was to get the pictures ID and pass it to a method which would then get all the comments for that picture
public void GetComments(long pictureID)
{
DBContext db = new DBContext();
Picture picture = new Picture();
//PictureComment comments = new PictureComment();
var comments = from c in db.PictureComments
where pictureID == c.PictureID
orderby c.DateTime descending
select c;
foreach (var comment in comments)
{
Console.WriteLine(picture.GetUsername(comment.UserID));
Console.WriteLine(comment.Comment);
}
}
I thought at first it was to do with being in a foreach loop, however the picture.GetUsername() method works fine.
Are there any SIMPLE work around, I say simple because I am new to c# and not aware of all the concepts/terminology. Thanks.
Upvotes: 2
Views: 2275
Reputation: 3105
You shouldn't use Console.WriteLine
and your method should return a MvcHtmlString
.
When you use the @
symbol before the method in your cshtml file, this means that the result from the method will be written in the resulting html.
this should work:
public MvcHtmlString GetComments(long pictureID)
{
DBContext db = new DBContext();
Picture picture = new Picture();
//PictureComment comments = new PictureComment();
var comments = from c in db.PictureComments
where pictureID == c.PictureID
orderby c.DateTime descending
select c;
StringBuilder sb = new StringBuilder();
foreach (var comment in comments)
{
sb.AppendLine(picture.GetUsername(comment.UserID));
sb.AppendLine(comment.Comment);
}
return new MvcHtmlString(sb.ToString());
}
This would solve your problem, but I suppose you would like to format the comments in some way in your html, so the best thing to do here is to return the list of your comments for a picture.
Then in your cshtml file, use a foreach
loop to iterate through them, and format them properly with the needed html.
Upvotes: 2