【问题标题】:MVC5 Razor NullReferenceException in Model模型中的 MVC5 Razor NullReferenceException
【发布时间】:2014-04-20 04:20:02
【问题描述】:

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

这是来自我的控制器的代码:

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 的代码:

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 属性具有正确的值,但是当我按 continue 时,它​​只会抛出错误。

有人有解决这个问题的办法吗?

【问题讨论】:

  • 在调试器中单步调试代码以确保所有对象都已初始化。看起来可能 Bar 在 Model 对象上为空
  • 这就是问题所在。它不为空,但仍然会引发错误。当我单步执行代码并将鼠标悬停在“.Name”上时,它将显示正确的值。
  • 你能发布堆栈跟踪吗?
  • 对此不确定。尝试使用快速查看检查下一个 C# 语句。
  • 您是否检查了

    @Model.Bar.Name

    之后的 C# 语句,发布堆栈跟踪肯定有助于解决问题。

标签: c# asp.net-mvc razor asp.net-mvc-5 nullreferenceexception


【解决方案1】:

有时编译器无法在剃刀视图中指向具有特定类型错误的确切行,这可能是因为它无法将它们的行号保留在堆栈跟踪或某处。我发现这种情况与 Null Reference Exception 以及在 Url.Content 中传递 null 时有关。

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

【讨论】:

猜你喜欢
  • 2015-02-06
  • 2019-01-12
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多