仅访问模型时的ASP.NET Core NullReferenceException

use*_*357 7 c# razor asp.net-core-mvc asp.net-core

我在尝试使用强类型模型创建视图时遇到问题.无论我作为模型传递给a View(),我总是会收到一个NullReferenceException甚至只是访问Model.

在执行剃刀页面的其余部分之前,我甚至无法检查模型是否为null; 简单地做一个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>
Run Code Online (Sandbox Code Playgroud)

EncodeProgress.cshtml

@page
@model FFenc.IEncoderModule

@{
    var module = Model; //this throws the NullReferenceException
}
Run Code Online (Sandbox Code Playgroud)

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

异常堆栈跟踪:

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

AspNetCore.Encoder_MVC_EncodeProgress.get_Model()
EncodeProgress.cshtml中的AspNetCore.Encoder_MVC_EncodeProgress.ExecuteAsync()
var module = Model;

我究竟做错了什么?我尝试了多个修复和变通方法(使用ViewComponent而不是视图),但没有任何作用.

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

索引视图中的ASP.NET Core Model null错误

我已经在模型中传递,所以这个答案并没有改变我正在做的事情.例如,当我尝试使用控制器作为解决方法时,NullReferenceException此代码也发生了同样的情况:

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

Jus*_*son 10

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