I have a MVC Razor DropDownFor that is throwing "Object Reference not set to instance of object" when i do a Submit. Im quite not sure how this error comes about.
In my Model i have:
public int BankId { get; set; }
public List<SelectListItem> Banks { get; set; }
The method that populates the SelectListItem as :
public static List<SelectListItem> PopulateBank()
{
List<SelectListItem> items = new List<SelectListItem>();
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SELECT BankId,BankName FROM Bank WHERE Active=" + Convert.ToInt32(Helpers.parameters.active) + "", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
items.Add(new SelectListItem
{
Text = Convert.ToString(dr["BankName"]),
Value = Convert.ToString(dr["BankId"])
});
}
conn.Close();
}
return items;
}
Then in the controller i have :
public ActionResult Bank ()
{
Models.Employee.Registration bank = new Models.Employee.Registration();
bank.Banks = PopulateBank();
return View(bank);
}
When I hit submit BankId is not getting any value:
[HttpPost]
public ActionResult Bank(FormCollection formcollection)
{
try
{
Models.Employee.Registration bank = new Models.Employee.Registration();
bank.Banks = PopulateBank();
bank.BankId = Convert.ToInt32(formcollection["BankId"]);
if (ModelState.IsValid)
{
using (SqlConnection conn1 = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SaveEmployeeBankDetail", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EmployeeNumber", bank.EmployeeNumber);
cmd.Parameters.AddWithValue("@BankId", bank.BankId); conn.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
ViewBag.ErrorMessage = Helpers.Messages.GENERAL_ERROR;
return View();
}
return RedirectToAction("Index");
}
In Bank.cshtml i have
<div class="col-sm-9">
<span class="input-icon">
@Html.DropDownListFor(m => m.BankId, Model.Banks, "", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BankId, "", new { @class = "text-danger" })
<i class="ace-icon fa fa-bank blue"></i>
</span>
</div>
What I have tried:
I have searched some sources online , suggestions are that i need to repopulate the DropDownListFor in the POST . As for the
model i have already passed it back into the view i.e in the GET version of
public ActionResult Bank. Please anyone to assist on how i can re-initialize this
model with the values.
Also is there anything i should do in Bank.cshtml regarding this ?