问题描述
我在尝试使用强类型模型创建视图时遇到麻烦.无论我将模型作为什么传递给View()
,即使只是访问Model
,我也总是收到NullReferenceException
.
I am having trouble with attempting to create a view with a strongly typed model. No matter what I pass in as the model to a View()
, I always receive a NullReferenceException
when even just accessing the Model
.
在执行剃刀页面的其余部分之前,我什至无法检查模型是否为空;只需执行if (Model != null)
也会抛出相同的NullReferenceException
.
I can't even check if the model is null before executing the rest of the razor page; simply doing a if (Model != null)
also throws the same 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();
}
异常堆栈跟踪:
AspNetCore.Encoder_MVC_EncodeProgress.get_Model()
EncodeProgress.cshtml中的AspNetCore.Encoder_MVC_EncodeProgress.ExecuteAsync()
var module = Model;
AspNetCore.Encoder_MVC_EncodeProgress.get_Model()
AspNetCore.Encoder_MVC_EncodeProgress.ExecuteAsync() in EncodeProgress.cshtml
var module = Model;
我做错了什么?我尝试了多种修复和解决方法(使用ViewComponent而不是视图),但是没有任何效果.
What am I doing wrong? I have attempted multiple fixes and workarounds (using a ViewComponent instead of a view) but nothing works.
我发现了一些类似的问题并没有解决我的问题:
Some similar questions that I have found that have not solved my problem:
我已经传递了模型,因此此答案不会改变我所做的任何事情.例如,当我尝试使用控制器作为解决方法时,此代码也发生了相同的NullReferenceException
:
I'm already passing in the model so this answer doesn't change anything about what I'm doing. For example, when I was trying to use a controller as a workaround, the same NullReferenceException
happened with this code:
[Route("/encode/progress")]
public IActionResult GetProgress()
{
return View("~/Encoder/MVC/EncodeProgress.cshtml", new EncoderModule());
}
推荐答案
我认为您正在混用剃刀页面.尝试删除@page
指令,并且您的模型应绑定到调用return View()
时传递的值.
I think you're mixing Razor Pages with ASP.NET MVC. Try removing the @page
directive and your model should be bound to the value passed when you call return View()
.
这篇关于仅在访问模型时的ASP.NET Core NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!