简体   繁体   English

PartialView模型为空,返回空引用

[英]PartialView model is empty returns null reference

I'm rendering a PartialView via an Action on my controller. 我正在通过控制器上的Action渲染PartialView。

This is sending a model to the partial which then populates a sub-list for each parent that the partial goes into. 这会将模型发送到局部,然后为局部所进入的每个父级填充一个子列表。

Some of the parent objects don't have children. 一些父对象没有孩子。

I need to capture an Id from the model in the partial to link the sub-list into an Accordion control. 我需要从局部模型中捕获一个ID,以将子列表链接到Accordion控件中。

How do I prevent a null reference exception when the child model is empty? 当子模型为空时,如何防止空引用异常?

Is there any way to send the ID direct from the Action? 有什么方法可以直接从操作中发送ID?

Current attempt... 当前尝试...

@using BootstrapSupport
@model IEnumerable<WhatWorks.ViewModels.FamilyListViewModel>

@{ if (string.IsNullOrEmpty(Model.FirstOrDefault().familyId.ToString()))
   {
     do something...
   }
   else
   {
    int modelIndex = Model.FirstOrDefault().familyId; 

Controller Action 控制器动作

    public ActionResult Index(int Id)
    {            
        var model = GetDisplay(Id).OrderBy(i => i.dob).AsEnumerable();            
        return PartialView("_family", model);
    }

Main View 主视图

var family = model.GetIdValue();
<div class="accordion" id="@Html.Raw("accordion")@family.Values.FirstOrDefault()@Html.Raw("_b")">
@Html.Action("Index", "Family", new { Id = family["Id"] })
</div>

ViewModel 视图模型

public partial class FamilyListViewModel
{
    public int Id { get; set; }
    public int familyId { get; set; }
    public string name { get; set; }
etc...
}

Then do this : 然后这样做:

@{ if (Model.Count() >0 )
   {
     do something...
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM