MVC4 -试图使用列表时在视图中抛出NullReferenceException

本文关键字:视图 NullReferenceException 列表 MVC4 | 更新日期: 2023-09-27 18:07:17

在我的主页(索引)上,我有两个部分,一个呈现搜索表单,另一个呈现搜索结果:

<div class="row-fluid well">
    <div class="span6">
        @Html.Partial("~/Views/Search/_BasicPropertySearchPartial.cshtml")
    </div>
    <div class="span6" id="basic-property-search-results">
        @Html.Partial("~/Views/Search/_BasicPropertySearchResultsPartial.cshtml")
    </div>
</div>

在我的SearchController中,GET操作返回搜索表单:

[HttpGet]
public ActionResult BasicPropertySearch()
{
    return PartialView("_BasicPropertySearchPartial");
}

POST操作从表单中获取用户输入,并根据查询返回结果:

[HttpPost]
public ActionResult BasicPropertySearch(BasicPropertySearchViewModel viewModel)
{
    var predicate = PredicateBuilder.True<ResidentialProperty>();
    if (ModelState.IsValid)
    {
        using(var db = new LetLordContext())
        {
            predicate = predicate.And(x => x.HasBackGarden);
            //...
            var results = db.ResidentialProperty.AsExpandable().Where(predicate).ToList();
            GenericSearchResultsViewModel<ResidentialProperty> gsvm = 
                    new GenericSearchResultsViewModel<ResidentialProperty> { SearchResults = results };
            return PartialView("_BasicPropertySearchResultsPartial", gsvm);
        }            
    }
    ModelState.AddModelError("", "Something went wrong...");
    return View("_BasicPropertySearchPartial");
}

我创建了一个通用视图模型,因为搜索结果可能是不同类型的列表:

public class GenericSearchResultsViewModel<T>
{
    public List<T> SearchResults { get; set; }
    public GenericSearchResultsViewModel()
    {
        this.SearchResults = new List<T>();
    }
}

POST操作返回以下视图:

@model LetLord.ViewModels.GenericSearchResultsViewModel<LetLord.Models.ResidentialProperty>
@if (Model.SearchResults == null) // NullReferenceException here!
{
    <p>No results in list...</p>
}
else
{
    foreach (var result in Model.SearchResults)
    {
    <div>
        @result.Address.Line1
    </div>
    }
}

我在GET和POST操作上设置了断点,并且在命中之前抛出异常。

这个问题是因为index.cshtmlSearchController中有机会做GET/POST之前被渲染而引起的吗?

如果是,这是否意味着这是一个路由问题?

最后,我认为new在构造函数中使用SearchResults可以克服NullReferenceExceptions ?

反馈感激。

MVC4 -试图使用列表时在视图中抛出NullReferenceException

看起来整个Model是空的。您需要为Html.Partial调用提供部分视图模型,或者使用Html.Action调用两个带有操作和控制器名称的控制器(子)操作。