将图像从数据库传递到视图,null参考异常错误



用户单击搜索按钮后,我想显示带有信息字段的列表,除了图像外,一切都很好。我有一个ActionResult方法,该方法从视图中获取ID并在单击事件中向用户显示给用户。

到目前为止的问题是,在控制器中,即使'item.image.imageid'具有ID值,左侧部分(我发送到视图的模型(,抛出null引用异常,因此我无法传递映像ID使用'href ="〜/process/..."'

的视图

屏幕检查错误:对象引用未设置为对象的实例。

我的控制器:

    [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类:

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

LetterInfo类:

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

返回图像文件的方法:

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

查看:

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

FormModel.Imageitem.Image是null。NullReferenceException是一个运行时错误,当您访问特定对象应该基于其类型的成员时,它会发生例如ImageId,例如。

相关内容

  • 没有找到相关文章

最新更新