25

For some reason I'm getting a NullReferenceException whenever I try to access my model.

Here is the code from my controller:

public async Task<ActionResult> Bar(string fooSlug, int barId)
{
    var foo = await mediaService.GetFoo(fooSlug);
    var bar = await barService.GetBarFromFooByTitleId(foo.TitleId, barId);
    var viewModel = new ViewModels.BarViewModel(foo, bar);
    return View(viewModel);
}

Code from the ViewModel:

public class BarViewModel
{
    public Models.Sub.FooDetails Foo{ get; set; }
    public Models.Sub.BarDetails Bar { get; set; }

    public BarViewModel(Models.Sub.FooDetails foo, Models.Sub.BarDetails bar) 
    {
        this.Foo = foo;
        this.Bar = bar;
    }
}

And my View:

@model FooBar.ViewModels.BarViewModel

@{
    ViewBag.Title = "Bar";
}

<h2>@Model.Bar.Name</h2>

It keeps returning a NullReferenceException When I try to use it inside the h2 tag. I've debugged it and the .Name property has the correct value, but when I press continue it will just throw the error.

Does anyone have a solution for this problem?

8
  • Step through the code in a debugger to ensure all objects are initialized. Looks like maybe Bar is null on the Model object Commented Mar 14, 2014 at 17:58
  • 1
    That is the problem. It's not null, but it still throws an error. When I step through the code and hover over the ".Name" it will show the proper value. Commented Mar 14, 2014 at 18:01
  • Could you post the stacktrace? Commented Mar 14, 2014 at 18:03
  • 2
    Not sure about this. Try to check the next C# statement using quick watch. Commented Mar 14, 2014 at 18:03
  • 1
    Did you checked the C# statement coming after <h2>@Model.Bar.Name</h2> Post the stack trace it will surely help to resolve the issue. Commented Mar 14, 2014 at 18:09

1 Answer 1

46

Some times compiler could not point on exact lines having specific kind of errors in razor view may be because it could not keep their line number in stack trace or somewhere. I have found this case with Null Reference Exception and when null is passed in Url.Content.

So it helps to check the next C# statement in razor view when you did not get any error on the line shown by stack trace.

Sign up to request clarification or add additional context in comments.

1 Comment

This helped me so much with my issue! Thank you! -- stackoverflow.com/questions/26491175/…

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.