0
votes

I'm rendering a PartialView via an Action on my controller.

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.

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?

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...
}
1
Can you post the rest of your view? I'd like to see how you're calling the partial. - John H
Would you also mind posting your model(s)? It's a little confusing trying to figure this out without seeing them. - John H
@JohnH I've added the ViewModel and the code in the main view that calls the partial. The error is caused by the ViewModel being empty for some of the partial views. - melkisadek

1 Answers

1
votes

Then do this :

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