相关疑难解决方法(0)

模型中的MVC5 Razor NullReferenceException

出于某种原因,每当我尝试访问我的模型时,我都会收到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);
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的观点:

@model FooBar.ViewModels.BarViewModel

@{
    ViewBag.Title = "Bar";
}

<h2>@Model.Bar.Name</h2>
Run Code Online (Sandbox Code Playgroud)

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

有没有人有这个问题的解决方案?

c# asp.net-mvc nullreferenceexception razor asp.net-mvc-5

23
推荐指数
1
解决办法
1万
查看次数