How to fix "Object Reference not set to an instance of an object"

shu tun 5 Reputation points
2023-12-21T01:37:29.2233333+00:00

theres values stored in viewbag as shown in the last picture , but error still popped. Help guysssss1

2

3

4

5

6

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-12-21T12:31:36.6366667+00:00

    Use ViewData to pass an object from a controller to a view in MVC Core. The following links illustrate how to configure the select tag helper.

    The Select Tag Helper

    https://code-maze.com/select-tag-helper-aspnetcore/

    https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper

    Example

    public IActionResult Index()
    {
        var options = new List<SelectListItem>() { 
            new SelectListItem()
            {
                Text = "Item 1",
                Value = "1"
            },
            new SelectListItem()
            {
                Text = "Item 2",
                Value = "3"
            }
        };
    
        ViewData["UnitId"] = options;
        return View();
    }
    

    View

    @model MvcDemo.Models.SelectModel
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <form>
        <select asp-for="UnitId" class="form-contorl" asp-items="@((List<SelectListItem>)ViewData["UnitId"])">
            <option value="">--Select--</option>
        </select>
    </form>
    

    I think there is a bug in your code that populates the select options since the ViewBag is null. If you share your code then we can help you figure that out as well.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.