模型中的 MVC5 Razor NullReferenceException [英] MVC5 Razor NullReferenceException in Model

查看:22
本文介绍了模型中的 MVC5 Razor NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,每当我尝试访问我的模型时都会收到 NullReferenceException.

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);
}

来自 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;
    }
}

还有我的观点:

@model FooBar.ViewModels.BarViewModel

@{
    ViewBag.Title = "Bar";
}

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

当我尝试在 h2 标签内使用它时,它不断返回 NullReferenceException.我已经调试了它并且 .Name 属性具有正确的值,但是当我按继续时它只会抛出错误.

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?

推荐答案

有时编译器无法指出在 razor 视图中具有特定类型错误的确切行,这可能是因为它无法在堆栈跟踪或某处保留它们的行号.我发现这种情况下存在 Null Reference Exception,并且在 Url.Content 中传递了 null.

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.

因此,当您在堆栈跟踪显示的行上没有收到任何错误时,在 razor 视图中检查下一个 C# 语句会很有帮助.

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.

这篇关于模型中的 MVC5 Razor NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆