This is to submit a view that uses ajax to pull the data.

I am trying to retrieve an image from MongoDb GridFS bucket. The download operation works. But the issue is, the view model that I use has:

public User User { get; set; }
public List<IFormFile> ImageUpload { get; set; }

I get the user from the db context, and use that to identify the image from the bucket and I want to return it to the view from the controller.

The following is my controller code:

public IActionResult AddEditUser(int id = 0)
        {
            if (id == 0)
            {
                return View(new UserImgBinder());
            }
            else
            {
                var userImageId = _context.User.Where(x => x.UserId.Equals(id)).Select(y => y.AvatarImg).ToString();
                var stream = ContextNew.ImagesBucket.OpenDownloadStream(new ObjectId(userImageId.ToBson()));
                var contentType = stream.FileInfo.Metadata["ContentType"].AsString;
                //File(stream, contentType);
                IFormFile file = new  FormFile(stream, 0, stream.Length,"",""); 


                var UserImgBinder = new UserImgBinder
                {
                    User = _context.User.Where(x => x.UserId.Equals(id)).FirstOrDefault(),
                    ImageUpload = file
            };
                return View(UserImgBinder);
            }

        }

Since ImageUpload is of type List and what I am trying to feed it is not a list I am getting error.

What should I write to solve this? Is this approach bad? Please help. Thanks.

1 Answers

0
Tao Zhou On Best Solutions

Try code like:

var UserImgBinder = new UserImgBinder
{
    User = _context.User.Where(x => x.UserId.Equals(id)).FirstOrDefault(),
    ImageUpload = new List<IFormFile> {
                file
            }
};