Handling null models in partials and null model values

14,719

Solution 1

I don't clearly understand what you mean with Model null, because your example check if UserId is null and not the Model itself. So, assuming you mean to check the entire Model, personally I will use a simple if at the start of my view. Something like this

 @model MyViewModel
 @if (Model != null) {
 <div>
    @Model.UserId
 </div>
 }

Or when you define the RenderSection pass the Required=false so when declaring the section, you can selectively do that if the model has value or not.

In your layout.cshtml

@RenderSection("Taskbar", false)

In your pages

 @if (Model != null) {
   section TaskBar{
     @Html.Partial("_TaskBar", Model);
   }
 }

Solution 2

In order to simplify your code you should utilize the Null Object pattern.

Instead of using null to represent a non existing value, you use an object initialized to empty/meaningless values. This way you do not need to check in dozens of places for nulls and get NullReferenceExpections in case you miss it.

There is even a simpler approach, derived from this. Instead of creating a specific NullObject class, just pass a new instance of the class you require. If it is a simple ViewModel, this usually is enough, since C# already initializes the values for you, and is likely what you want most of the time.

Share:
14,719
billy jean
Author by

billy jean

Hi There!

Updated on June 07, 2022

Comments

  • billy jean
    billy jean about 2 years

    i am having problems figuring out how to handle nulls when passing models to partials as well handling null values in models.

    In this block:

    @section TaskBar{
         @Html.Partial("_TaskBar", Model);
    }
    

    I get this error: e:\Views\Shared_TaskBar.cshtml(107): error CS1002: ; expected

    ???

    also, having problem with nulls in the partial

    I've tried: this.userID = ko.observable("@if(Model.UserID == null){"null"}else{Model.UserID}");

    and

    this.userID = ko.observable("@(Model.UserID == null)?"null" :Model.UserID");
    

    with ; etc...

    So my question is.. my partial will often be passed a null model.. so how to handle the partial method and if null how to handle in the view? thanks!