I am currently using this method in different view with no error, yet it is now giving error in a new view-
System.NullReferenceException: ‘Object reference not set to an instance of an object.’
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get returned null.
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=Website StackTrace:atAspNetCoreGeneratedDocument.Views_Post_Create.<< ExecuteAsync >b__53_19>d.MoveNext() in G:…ViewsPostCreate.cshtml:line 54
I am using a database table for my dropdown list. I first tried using IEnumerable
but it resulted in same error. I used google but couldn’t resolve my error. Here is my code-
Model:
public class PostCategoryModel
{
[Key]
public int Id { get; set; }
public string CategoryName { get; set; }
}
ViewModel:
public class CreatePostViewModel
{
// Code before
public List<PostCategoryModel>? PostCategoryList { get; set; }
}
View:
<div class="col-md-12 mb-3">
<label asp-for="PostCategory" class="form-label">Post Category</label>SelectList(Model.PostCategoryList,"Value", "Text"))" class="form-select" required>*@
<select asp-for="PostCategory" class="form-select">
<option hidden selected>Open this select menu</option>
@foreach (var item in Model.PostCategoryList)
{
<option value="@item.Id">@item.CategoryName</option>
}
</select>
<div class="invalid-feedback">
Please select a valid category.
</div>
</div>
2
Answers
I was initializing
PostCategoryList
incorrectly, hence it was returning null value.Here is what I was doing (wrong method) :
Controller-
Correct method of initialization :
Controller-
Before sending the view model into view, be sure that view model is filled correctly.
In your httpget action where you want to return the view be sure that view model is filled like this:
Also, because of List<PostCategoryModel?, null is possible and when it wants to foreach, it throws null exception and you can handle something like this:
and to refer with your talk "I am currently using this method in different view with no error" maybe inside that method, you initialized the List<PostCategoryModel? inside the constructor.