代码之家  ›  专栏  ›  技术社区  ›  MattSull

MVC4-尝试使用列表时在视图中引发NullReferenceException

  •  0
  • MattSull  · 技术社区  · 11 年前

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

    <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.cshtml 在有机会在 搜索控制器 ?

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

    最后,我想 new 惯性导航与制导 SearchResults 在构造函数中会克服 NullReferenceExceptions ?

    感谢反馈。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Peit    11 年前

    看起来整个 Model 为null。您需要将局部视图模型提供给 Html.Partial 呼叫或使用 Html.Action 用动作和控制器名称调用两个控制器(子)动作。

    请参阅 MSDN 详细信息。