skip to Main Content

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>

The problem has ben solved. I have posted my solution here

2

Answers


  1. Chosen as BEST ANSWER

    I was initializing PostCategoryList incorrectly, hence it was returning null value.


    Here is what I was doing (wrong method) :

    Controller-

    public IActionResult Create()
    {
        return View();
    }
    
    [HttpPost]
    public async Task<IActionResult> Create(CreatePostViewModel postVM)
    {
        if (ModelState.IsValid)
        {
            postVM = new CreatePostViewModel
            {
                PostCategoryList = await _context.PostCategories.ToListAsync()
            };
    
            var post = new PostModel
            {
                PostCategory = postVM.PostCategory,
            };
    
            // Code
        }
        else
        {
            // Error
        }
        return View(postVM);
    }
    

    Correct method of initialization :

    Controller-

    public async Task<IActionResult> CreateAsync()
    {
       var CreatePostCategoryVM = new CreatePostViewModel
       {
           PostCategoryList = await _context.PostCategories.ToListAsync()
       };
    
        return View(CreatePostCategoryVM);
    }
    
    [HttpPost]
    public async Task<IActionResult> Create(CreatePostViewModel postVM)
    {
        if (ModelState.IsValid)
        {
            var post = new PostModel
            {
                PostCategory = postVM.PostCategory,
            };
    
            // Code
        }
        else
        {
            // Error
        }
        return View(postVM);
    }
    

  2. 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:

     var viewModel = new CreatePostViewModel();
     viewModel.PostCategoryList = GetPostCategories(); // Fetch data from db
     return View(viewModel);
    

    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:

    @if (Model.PostCategoryList != null && Model.PostCategoryList.Any())
    {
        <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>
            }
        }
    }
    else
    {
        <p>No categories available.</p>
    }
    

    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.

    public class CreatePostViewModel
    {
        public List<PostCategoryModel> PostCategoryList { get; set; }
    
        public CreatePostViewModel()
        {
            PostCategoryList = new List<PostCategoryModel>();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search