Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# foreach循环在mvc视图中为所有帖子显示相同的图像_C#_Asp.net_Asp.net Mvc_Linq_Entity Framework - Fatal编程技术网

C# foreach循环在mvc视图中为所有帖子显示相同的图像

C# foreach循环在mvc视图中为所有帖子显示相同的图像,c#,asp.net,asp.net-mvc,linq,entity-framework,C#,Asp.net,Asp.net Mvc,Linq,Entity Framework,我似乎无法在我的应用程序中显示每个帖子的单独图片。所有图片都与列表中的最后一张相同。我需要将每个post中的图片转换为base64。在控制器中,我试图抓取每个post对象并将Picture属性转换为base64,然后将其添加到ViewBag.ImageToShow,但是ImageToShow只能保存一个项目,因此所有我的图像都设置为我的posts列表中的最后一个图像。如果我为ViewBag创建一个列表,作为下面提到的答案之一,我不知道如何正确索引它们 型号: public partial

我似乎无法在我的应用程序中显示每个帖子的单独图片。所有图片都与列表中的最后一张相同。我需要将每个
post
中的
图片
转换为base64。在控制器中,我试图抓取每个post对象并将Picture属性转换为base64,然后将其添加到
ViewBag.ImageToShow
,但是
ImageToShow
只能保存一个项目,因此所有我的图像都设置为我的
posts
列表中的最后一个图像。如果我为
ViewBag
创建一个
列表
,作为下面提到的答案之一,我不知道如何正确索引它们

型号:

    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; }
    }
}
视图:

@for(int i=0;iitem.ShortDescription)

@ActionLink(“编辑”,“编辑”,新的{id=item.id})| @ActionLink(“详细信息”,“详细信息”,新的{urlslaug=item.urlslaug})| @ActionLink(“删除”,“删除”,新的{id=item.id}) } }

请注意,在视图中,我在创建动态布局时将
viewbag.Imagetoshow
放置在foreach循环中。对于posts列表中的每个图像,显示图像。但是,我无法将viewbag存储为列表并返回与每个视图相关的正确图像,同时必须将图像转换为base64。

如果将每个图片指定给同一个viewbag属性,通常您总是看到相同的图片

应向模型中添加一个名为ImageToShow的新字符串属性,该属性标记为NotMapped属性:

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

    [NotMapped]
    public string ImageToShow { get; set; }

    public virtual BlogUser BlogUser { get; set; }
    public virtual Category Category { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}
公共部分类职位
{
公职人员职位()
{
this.Tags=newhashset();
}
公共int Id{get;set;}
公共字符串BlogUserEmail{get;set;}
public int CategoryId{get;set;}
公共字符串标题{get;set;}
公共字符串ShortDescription{get;set;}
公共字符串说明{get;set;}
公共字符串元{get;set;}
公共字符串UrlSlug{get;set;}
公共bool已发布{get;set;}
public System.DateTime PostedOn{get;set;}
公共可空修改{get;set;}
公共字节[]图片{get;set;}
[未映射]
公共字符串ImageToShow{get;set;}
公共虚拟BlogUser BlogUser{get;set;}
公共虚拟类别{get;set;}
公共虚拟ICollection标记{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());
    }
    public ActionResult Index()
    {
        var posts = new List<MvcApplication2.Models.Post>();
        foreach (var item in posts) // this is wrong 
        {
            byte[] buffer = item.Picture;
            item.ImageToShow = Convert.ToBase64String(buffer);
        }
        return View(posts.ToList());
    }
public ActionResult Index()
{
var posts=新列表();
foreach(posts中的var项)//这是错误的
{
字节[]缓冲区=项。图片;
item.ImageToShow=Convert.tobase64字符串(缓冲区);
}
返回视图(posts.ToList());
}
视图:

@for(int i=0;iitem.ShortDescription)

@ActionLink(“编辑”,“编辑”,新的{id=item.id})| @ActionLink(“详细信息”,“详细信息”,新的{urlslaug=item.urlslaug})| @ActionLink(“删除”,“删除”,新的{id=item.id}) } }
你做错了!将所有图像存储在同一个变量中

public ActionResult Index()
{
    var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);

        // this is what you should do, or something like this
        ViewBag.ImagesToShow = new List<String>();

    foreach (var item in posts)
    {
        byte[] buffer = item.Picture;

        // this is really wrong!
        //ViewBag.ImageToShow = Convert.ToBase64String(buffer);

        ViewBag.ImagesToShow.Add(Convert.ToBase64String(buffer));
    }
    return View(posts.ToList());
}
public ActionResult Index()
{
var posts=db.posts.Where(p=>p.BlogUserEmail==User.Identity.Name)。Include(p=>p.BlogUser)。Include(p=>p.Category);
//这是你应该做的,或者类似的事情
ViewBag.ImagesToShow=新列表();
foreach(POST中的var项目)
{
字节[]缓冲区=项。图片;
//这真的错了!
//ViewBag.ImageToShow=Convert.TOBASE64字符串(缓冲区);
ViewBag.ImagesToShow.Add(Convert.ToBase64String(buffer));
}
返回视图(posts.ToList());
}

您还需要更改视图。代码的问题在于控制器中索引函数的循环。您正在循环中设置
ViewBag.ImageToShow
,该变量只能保存一个对象,因此通过在循环中设置它,它会不断重置

这里有两个选项:

使用ViewBag

在控制器中,创建一个字典,分别保存int、string、ID和value。在循环中,您需要为找到的每个图像添加一个条目

    public ActionResult Index()
    {
        Dictionary<int, string> postImages = new Dictionary<int, string>();
        var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);
        foreach (var item in posts) 
        {
            byte[] buffer = item.Picture;
            postImages.Add(item.ID, Convert.ToBase64String(buffer));
        }
        ViewBag.Images = postImages;
        return View(posts.ToList());
    }
根据要求提供完整示例:

@{Dictionary<int, string> images = (Dictionary<int, string>)ViewBag.Images;
@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," + images.Single(image => image.Key == item.ID).Value)" 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>
  }
}
现在,在控制器内部,我们必须创建新创建模型的新列表,并用所需数据填充该列表:

    public ActionResult Index()
    {
        List<PostImageModel> postsWithImages = new List<PostImageModel>();
        var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);
        foreach (var item in posts) 
        {
            item.Picture = null;
            postsWithImages.Add(new PostImageModel()
            {
                Post = item,
                Image = Convert.ToBase64String(item.Picture)
            });
        }
        return View(postsWithImages);
    }
public ActionResult Index()
{
List postsWithImages=新列表();
var posts=db.posts.Where(p=>p.BlogUserEmail==User.Identity.Name)。Include(p=>p.BlogUser)。Include(p=>p.Category);
foreach(POST中的var项目)
{
item.Picture=null;
添加(新的PostImageModel()
{
Post=项目,
Image=Convert.tobase64字符串(item.Picture)
});
}
返回视图(postsWithImages);
}
编辑:添加,以便代码在转换完字节数组后将其清空。(谢谢@Serv)

您的循环将保持不变,除了不使用
item.Title
之外,您现在应该使用
item.Post.Title


请注意,现在您应该在视图顶部添加
@model exampleMespace.Models.PostImageModel
,以便使用此模型。

有几种方法可以做到这一点。第一个也是最快的方法是将所有图像放在一个集合中,然后将该集合存储在ViewBag中。现在,y
var images = (Dictionary<int, string>)ViewBag.Images;
images.Single(i => i.Key == item.ID).Value;
@{Dictionary<int, string> images = (Dictionary<int, string>)ViewBag.Images;
@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," + images.Single(image => image.Key == item.ID).Value)" 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>
  }
}
public class PostImageModel
{
    public Post Post { get; set; }
    public string Image { get; set; }
}
    public ActionResult Index()
    {
        List<PostImageModel> postsWithImages = new List<PostImageModel>();
        var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);
        foreach (var item in posts) 
        {
            item.Picture = null;
            postsWithImages.Add(new PostImageModel()
            {
                Post = item,
                Image = Convert.ToBase64String(item.Picture)
            });
        }
        return View(postsWithImages);
    }
public ActionResult Index()
{
    var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name).Include(p => p.BlogUser).Include(p => p.Category);

    // create collection
    List<string> ImageCollection = new List<string>();
    foreach (var item in posts)
    {
        //add images to list
        ImmageCollection.Add(Convert.ToBase64String(item.Picture));
    }
    //Add list to ViewBag
    ViewBag.ImageToShow = ImageCollection;
    return View(posts.ToList());
}
<img class="img-responsive" src="@Html.Raw("data:image/jpeg;base64," + ViewBag.ImageToShow[i])" alt="">
public class PortfolioVM
{
    public int Id { get; set; }
    public string UrlSlug { get; set; }
    //not Byte[]!
    public string Picture { get; set; }
    public string ShortDescription { get; set; }
}
public ActionResult Index()
{
    var posts = db.Posts.Where(p => p.BlogUserEmail == User.Identity.Name)
                        .Include(p => p.BlogUser)
                        .Include(p => p.Category)
                        .Select(vm => new PortfolioVM(){
                            Id = vm.Id,
                            UrlSlug = vm.UrlSlug,
                            Picture = Convert.ToBase64String(vm.Picture),
                            ShortDescription = vm.ShortDescprition
                         }) ;

    return View(posts);
}
//insert correct namespace!
@model IEnumerable<Namespace.Subfolder.PortfolioVM)
    @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," + item.Picture)" 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>
    }