0

I'm building an ASP.NET 4.5 MVC Web Application with partial views and a nested view model.

The problem: the view model is intially null... I need to create an input for SwotPartVm.Label and should put no logic in the View.

Do you have any suggests on how to solve this issue ?

Thanks :)

index.cshtml:

@foreach (var swot in Model.Swots)
{
    foreach (var swotPart in swot.SwotParts)
    {
        @Html.Partial("~/Views/Shared/_SwotPart.cshtml", swotPart)
    }
}

viewmodels: I need to create an input for SwotPartVm.Label...

public class OfferVM
{
    public int OfferId { get; set; }

    public List<SWOTVM> Swots { get; set; } 
}

public class SWOTVM
{
    // enum
    public SwotFor SwotForId { get; set; }
    public List<SwotPartVm> SwotParts { get; set; }
}

public class SwotPartVm
{
    public string Label { get; set; }
    // enum
    public SwotType SwotTypeId { get; set; }
}
TimHorton
  • 865
  • 3
  • 13
  • 33
  • 2
    If `Model` could be null, Add a null check before `Model.Swots` usage – Shyju Mar 07 '17 at 18:33
  • 2
    "The problem: the view model is intially null" - well why is that? Why not change your controller to ensure the model is never null. – Jon Skeet Mar 07 '17 at 18:36
  • Thanks Shyju, the idea is to create input fields for each SwotPart.Label and to let the user fill out the swot form to create the Swot Objects... when the view initially renders it crashes beacause of null... i need to somehow initialze the Model.Swots – TimHorton Mar 07 '17 at 18:38
  • 1
    In the constructor for your `OfferVM` model, just do `SwotParts = new List();` to initialise an empty list. – DavidG Mar 07 '17 at 18:39
  • 1
    @TimHorton initialize Model.Swots in your constructor – AWinkle Mar 07 '17 at 18:40
  • thanks guys for your help! – TimHorton Mar 07 '17 at 18:46

0 Answers0