Stainn
Stainn

Reputation: 119

Error while trying populate DropDownListFor from Database

I am trying to populate the DropDownListFor items from the database, but when I tried to run the program, it gives me error Object reference not set to an instance. Like the method (Get data from the database and put it into SelectList) did not get called at all, even though I have called and set it from the Controller.

Could you please tell me what is going wrong?

Here is the code that I am using:

Get data from the database: (Inventory class) (Row Id from table below is there by default when we created the database)

private string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\db1.mdf;Integrated Security=True";

[Display(Name = "ModuleData:")]
public string ModuleData
    {
        get;
        set;
    }

public string ID
    {
        get;
        set;
    }

public string Name
    {
        get;
        set;
    }

public IEnumerable<SelectListItem> ListData
    {
        get;
        set;
    }

public SelectList GetData()
        {
            List<SelectListItem> lists = new List<SelectListItem>();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string query = "SELECT [Id], [Name] FROM [Query]";

                conn.Open();

                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            ID = reader["Id"].ToString();

                            Name = reader["Name"].ToString();

                            lists.Add(new SelectListItem() { Text = Name, Value = ID });
                        }
                    }
                }

                conn.Close();
            }

            return new SelectList(lists, "Value", "Text");
        }

Controller:

Inventory repository = new Inventory();

[HttpGet]
public ActionResult Module()
        {
            repository.ListData = repository.GetData();

            return View();
        }

[HttpPost]
public ActionResult Module(Inventory inven)
        {
            // There is a button later on and here I want to get the value of a selected `DropDownListFor`
            return View(inven);
        }

View (Module):

@model Project_Name.Inventory
@{
    ViewBag.Title = "Inventory";
}

<h2>Inventory</h2>
<br />

@using (Html.BeginForm())
{
    <div>
        <fieldset>
            <legend>Inventory</legend>
            <div class="editor-label">
                @Html.LabelFor(u => u.ModuleData)
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(u => u.ID, Model.ListData)
            </div>
        </fieldset>
    </div>
}

Above is the code that I am using, but once I ran the program, it gives me error on @Html.DropDownListFor(u => u.ID, Model.ListData) says that Object reference not set to an instance of an object.

That is all of my question.

Thank you very much

Your answer much appreciated.

Upvotes: 1

Views: 57

Answers (2)

user3559349
user3559349

Reputation:

In your GET method, your assign the SelectList used by @Html.DropDownList() using

repository.ListData = repository.GetData();

however in the when you POST and return the view, you do not reassign the SelectList, hence Model.ListData is null. Your need to repeat the above line of code immediately before your call return View(inven);

You also need to return your model in the GET method

repository.ListData = repository.GetData();
return View(repository); // change this

Upvotes: 1

Crowcoder
Crowcoder

Reputation: 11514

You are calling GetData but not doing anything with the result. You need to feed the model to the view or else it is null:

[HttpGet]
public ActionResult Module()
{
    repository.ListData = repository.GetData();
    return View(repository);
}

Upvotes: 1

Related Questions