我已经google了一下,但仍然没有找到我正在寻找的东西。我想要发生的是获取已发布的特定图像的所有评论。
@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>
}
返回的错误是无法将类型'void'隐式转换为'object'
计划是获取图片ID并将其传递给一个方法,然后获取该图片的所有评论
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);
}
}
我首先想到的是处于foreach循环中,但是 picture.GetUsername()方法可以正常工作。
有没有SIMPLE可以解决的问题,我说这很简单,因为我是c#的新手,并且不了解所有的概念/术语。 感谢。
答案 0 :(得分:2)
您不应该使用Console.WriteLine
,并且您的方法应该返回MvcHtmlString
。
当您在cshtml文件中的方法之前使用@
符号时,这意味着该方法的结果将写入生成的html中。
这应该有效:
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());
}
这可以解决你的问题,但我想你想在你的html中以某种方式格式化评论,所以这里最好的办法是返回你的评论列表。
然后在你的cshtml文件中,使用foreach
循环来迭代它们,并使用所需的html正确格式化它们。