gpt4 book ai didi

c# - 公共(public)无效方法不起作用。无法将类型 'void' 隐式转换为 'object'

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:10 26 4
gpt4 key购买 nike

我已经用谷歌搜索了,但仍然没有找到我要找的东西。我想要发生的是获取已发布的特定图像的所有评论。

@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>
}

返回的错误是Cannot implicitly convert type 'void' to '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() 方法工作正常。

是否有任何简单的解决方法,我说简单是因为我是 c# 的新手并且不了解所有概念/术语。谢谢。

最佳答案

你不应该使用 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 正确格式化它们。

关于c# - 公共(public)无效方法不起作用。无法将类型 'void' 隐式转换为 'object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21731796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com