asp.net-mvcentity-frameworkloadimage

The parameter 'inArray' is coming null. Why?


I'm trying to load an image from a database.

I used this code in my view :

@foreach (var item in ViewBag.Base64String)
{
    var base64 = Convert.ToBase64String(item.ImageData);
    var imgSrc = String.Format("data:image/jpg;base64,{0}", base64);

    <p>id:@item.NewsId</p>
    <img alt="" src="@imgSrc" style="height:100px;width:100px;" />
}

but I get this error in the browser:

Value cannot be null.Parameter name: inArray

My model class:

public class News
{
    [Key]
    public int NewsId { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public byte[] ImageData { get; set; }
    public string MainComment { get; set; }
}

My controller :

WebContext db = new WebContext();

public ActionResult News()
{
       ViewBag.Base64String = db.AllNews.ToList();
       return View();
}

What's the problem?


Solution

  • According to the docs, inArray is null refers to ArgumentNullException.

    It means, in some of your records, the field ImageData is empty or null, which throws exception by ToBase64String.

    you may use if-clause and set a default image, in case a record has no ImageData; for instance:

    @if(item.ImageData != null) {  
            var base64 = Convert.ToBase64String(item.ImageData);  
            var imgsrc = string.Format("data:image/jpg;base64,{0}", base64); 
            <img src = '@imgsrc'  
            style = "max-width:100px;max-height:100px" / >  
        }  
        else { 
              <img src = "~/img/avatar-default.jpg"  
                       style = "max-width:100px;max-height:100px" / > 
        }