【发布时间】:2015-04-26 12:48:33
【问题描述】:
我似乎无法在我的应用程序中显示每个帖子的单独图片。所有图像都与列表中的最后一个相同。我需要将每个post 中的Pictures 转换为base64。在控制器中,我试图抓取每个帖子对象并将 Picture 属性转换为 base64,然后将其添加到 ViewBag.ImageToShow,但是 ImageToShow 只能容纳一个项目,因此我的所有图像都设置为我的 posts 中的最后一个图像列表。如果我为ViewBag 创建一个list<string> 作为下面提到的答案之一,我不知道如何正确索引它们。
型号:
public partial class Post
{
public Post()
{
this.Tags = new HashSet<Tag>();
}
public int Id { get; set; }
public string BlogUserEmail { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public string Meta { get; set; }
public string UrlSlug { get; set; }
public bool Published { get; set; }
public System.DateTime PostedOn { get; set; }
public Nullable<System.DateTime> Modified { get; set; }
public byte[] Picture { get; set; }
public virtual BlogUser BlogUser { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
控制器:
public ActionResult Index()
{
var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);
foreach (var item in posts) // this is wrong
{
byte[] buffer = item.Picture;
ViewBag.ImageToShow = Convert.ToBase64String(buffer);
}
return View(posts.ToList());
}
查看:
@for (int i = 0; i < Model.Count(); i += 3)
{
<div class="row">
@foreach (var item in Model.Skip(i).Take(3))
{
<div class="col-md-4 portfolio-item">
<a href="@Url.Action("Details", "Post", new { urlslug = item.UrlSlug })">
<img class="img-responsive" src="@Html.Raw("data:image/jpeg;base64," + ViewBag.ImageToShow)" alt="">
</a>
<h3>
<a href="@Url.Action("Details", "Post", new { urlslug = item.UrlSlug })">@Html.DisplayFor(modelItem => item.Title)</a>
</h3>
<p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { urlslug = item.UrlSlug }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</div>
}
</div>
}
请注意,在创建动态布局时,我将 viewbag.Imagetoshow 放在 foreach 循环中。对于帖子列表中的每个图像,显示图像。但是,我无法将 viewbag 存储为列表并返回与 foreach 视图相关的正确图像,同时必须将图像转换为 base64。
【问题讨论】:
标签: c# asp.net asp.net-mvc linq entity-framework