Search code examples
c#asp.netasp.net-mvcentity-frameworkasp.net-identity

Pass Image from Database to View, Null Reference Exception Error


After user click on search button, I want to show a list with info fields, all is fine except one for Image. I have a ActionResult method that takes an Id from the view and show image to user on click event.

The problem so far is that in controller even if 'item.Image.ImageId' has an Id value, the left part (Model that I send to the view), throws Null Reference Exception so I can't pass Image Id to the View with 'href = "~/Process/..."'

Screenshoot Error: Object reference not set to an instance of an object.

My controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(SearchModel FormModel)
    {
        int districtNo = Convert.ToInt32(FormModel.DistrictNo);
        List<SearchModel> ResultsList = new List<SearchModel>();

        IQueryable<LetterInfo> DbQueries = // Get result from db

        foreach (var item in DbQueries.ToList())
        {
            FormModel.FirstName = item.FirstName;
            FormModel.LastName = item.LastName;
            ...
            FormModel.Image.ImageId = item.Image.ImageId; 
// FromModel.Image.ImageId - null reference exception
            ResultsList.Add(FormModel);

        }
        ViewBag.ResultsToView = ResultsList;
    }
        return View(new SearchModel());
    }

SearchModel class:

public class SearchModel
{
    .
    .
    .
    public Image Image { get; set; }
}

LetterInfo class:

 public class LetterInfo
 {   
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int LetterId { get; set; }
    .
    .
    .
    public virtual Image Image { get; set; }
 }   

Method that returns a image file:

    public ActionResult ViewImage(int Id)
    {
        var img = db.Images.First(a => a.ImageId == Id);
        var stream = new MemoryStream(img.FileContents);

        var lname = "letter" + Path.GetExtension(img.FileName)?.ToLower();

        Response.AppendHeader("Content-Disposition", $"inline; filename={lname}");
        return File(stream, Helpers.GetMimeType(img.FileName));
    }

View:

@model SearchModel

@section scripts{
  <script type="text/javascript">
    var win;

    $('#openImage').click(function (event) {
        event.preventDefault();
        win = window.open(this.href, 'child', 'resizable=1');
        return false;
    });
  </script>
}
...
@foreach (var item in ModelList){
  <li></li> 
  ...
  <li class="list-group-item">
    <a href="~/Process/ViewImage/@item.Image.ImageId" id="openImage"> 
<!-- On click open image file -->

      <span>Click to see image</span>
    </a>
  </li>
}

Solution

  • Either FormModel.Image or item.Image is null. A NullReferenceException is a runtime error that occurs when you access a member that a particular object should have based on its type, but actually doesn't have because the instance is null, and null does not have a property like ImageId, for example.