3

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!

2 Answers 2

10

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);
   }
 }
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.