MVC5剃刀的NullReferenceException在型号 [英] MVC5 Razor NullReferenceException in Model

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

问题描述

出于某种原因,我得到一个NullReferenceException每当我尝试访问我的模型。

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

下面是从我的控制器code:

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:

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>

它保持返回一个NullReferenceException当我尝试使用它的H2标签​​内。我已经调试它和.Name点属性有正确的价值,但是当我preSS继续它只会抛出错误。

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?

推荐答案

有些时候,编译器上具有特定类型的错误,在剃刀观点可能是准确的线不能点,因为它不能保持堆栈跟踪或其他地方的行号。我发现这种情况下,与空引用异常,当空的Url.Content传递。

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.

所以它有助于检查剃刀查看下一个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剃刀的NullReferenceException在型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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