0

I have a View which can be accessed when the Model is populated with data and when the Model is completely empty.

When the Model is empty, it means that the user clicked on "Create New".

At the moment, I am getting a NullReferenceException because there obviously isn't anything inside Model. If I pass an object over to the view then the browser just freezes because the object contains null items inside it.

Is there a quicker/better way of doing this instead of doing: MyObject myObj = new MyObj(); myObj.InnerObj = new Object(){data = ....}; ...

I hope that makes sense :)

2 Answers 2

1

You can use the NullObject pattern:

Create a subclass of MyObject that has all properties prepopulated and methods that purposefully implement no behavior. For instance:

public sealed class NullObject : MyObject
{
    public object InnerObj { get; private set; }
    public NullObject()
    {
        InnerObj = new Object { ... };
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

It may not be the most clever way to deal with it, but I will sometimes wrap the Model-dependent code in the view in

@if(Model.Property != null)

So if you're having a single view for 'Create' and 'Edit', with the difference being the population of properties in the model, test those properties with an 'if', then code accordingly.

A better solution (I think) that we eventually implemented is an enum that we call "EditState" with two values: 'create' and 'edit'. Make the EditState a property in the viewModel. Set or check it's value and render the view accordingly (either with inputs for create, or displays or however you're setting it up.) It's a nice and easy to read way to differentiate between the create flow and the edit flow.

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.