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
.
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();
}
Exception stack trace:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Encoder_MVC_EncodeProgress.get_Model()
AspNetCore.Encoder_MVC_EncodeProgress.ExecuteAsync() in EncodeProgress.cshtml
var module = Model;
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:
ASP.NET Core Model null error in the Index view
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());
}