【问题标题】:ASP.NET Core NullReferenceException when just accessing model仅访问模型时的 ASP.NET Core NullReferenceException
【发布时间】:2018-08-25 03:25:09
【问题描述】:

我在尝试使用强类型模型创建视图时遇到问题。无论我将什么作为模型传递给View(),即使只是访问Model,我总是会收到NullReferenceException

在执行剃刀页面的其余部分之前,我什至无法检查模型是否为空;只需执行 if (Model != null) 也会抛出相同的 NullReferenceException

Index.cshtml

@page
@model EncodeModel
@{
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h2>Encode</h2>

<div id="progress">
    @await Html.PartialAsync("~/Encoder/MVC/EncodeProgress.cshtml", new EncodeModule())
</div>

EncodeProgress.cshtml

@page
@model FFenc.IEncoderModule

@{
    var module = Model; //this throws the NullReferenceException
}

Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc();
    }

异常堆栈跟踪:

NullReferenceException:对象引用未设置为对象的实例。

AspNetCore.Encoder_MVC_EncodeProgress.get_Model()
EncodeProgress.cshtml 中的 AspNetCore.Encoder_MVC_EncodeProgress.ExecuteAsync()
var 模块 = 模型;

我做错了什么?我尝试了多种修复和解决方法(使用 ViewComponent 而不是视图),但没有任何效果。

我发现的一些类似问题并没有解决我的问题:

ASP.NET Core Model null error in the Index view

我已经传递了模型,所以这个答案不会改变我正在做的任何事情。例如,当我尝试使用控制器作为解决方法时,同样的NullReferenceException 发生在这段代码中:

    [Route("/encode/progress")]
    public IActionResult GetProgress()
    {
        return View("~/Encoder/MVC/EncodeProgress.cshtml", new EncoderModule());
    }

【问题讨论】:

    标签: c# razor asp.net-core asp.net-core-mvc


    【解决方案1】:

    我认为您正在将 Razor Pages 与 ASP.NET MVC 混合使用。尝试删除 @page 指令,您的模型应该绑定到调用 return View() 时传递的值。

    【讨论】:

    • 谢谢,这解决了它。 Resharper 在没有 @page 指令的情况下将 Model 变量标记为未定义,但我发现了另一个关于它的问题:stackoverflow.com/questions/33130521/…。再次感谢!
    • 请注意,其他问题无关。 ASP.NET Core(包括 MVC 和 Razor Pages)是一个相当新的开发框架,而 ASP.NET MVC(not Core)已经存在了将近十年。 Razor Pages 特别是我认为只有大约一年的历史。如果你是新手,这可能会有点混乱。有很多重叠之处,但也有不同之处。 Core 绝对是任何新开发的必经之路。我只是想让你知道,这样你才能走上正轨。
    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2018-07-09
    • 2018-04-02
    • 2019-09-28
    • 2017-07-22
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多