将数据从数据库传递到视图,空引用异常错误

时间:2017-06-07 13:14:20

标签: c# asp.net asp.net-mvc entity-framework asp.net-identity

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

到目前为止的问题是在控制器中,即使'item.Image.ImageId'有一个Id值,左边的部分(我发送给视图的模型),抛出Null Reference Exception,所以我无法传递Image Id使用'href =“〜/ Process /..."'

查看视图

屏幕截图错误:Object reference not set to an instance of an object.

我的控制器:

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

1 个答案:

答案 0 :(得分:0)

FormModel.Imageitem.Image为空。 NullReferenceException是一个运行时错误,当您根据其类型访问某个特定对象 所拥有的成员时发生,但实际上由于该实例为null而没有,并且例如,null没有ImageId之类的属性。