I have this:
@Html.DropDownList("centres", (List<SelectListItem>)ViewData["centres"])
And I need to update it with data entered into the database with SQL while the program is running, using JQuery:
jQuery(function ($) {
jQuery("body").on('click', "#create", function () {
$.getJSON("/Centres/updateList", function (results1) {
// perform update here using results1 from jsonresult updateList in Controller class
});
});
});
The results1 is a List from my MVC controller class. I'd like to be able to edit my existing html dropdownlist with these new results. Currently it displays a list of selectListItems, but in updateList in the controller class I am creating a new list, based on a new centre I have just created. My Controller class method looks like this:
public JsonResult updateList()
{
List<SelectListItem> centres = new List<SelectListItem>();
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Michael\Documents\Visual Studio 2012\Projects\OneEightyWebApp\OneEightyWebApp\App_Data\OneHoldings.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT Centre.Centre_Name, Count(Shop_No) AS Shop_Count FROM Centre LEFT JOIN Space ON Centre.Centre_Name = Space.Centre_Name GROUP BY Centre.Centre_Name;", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(dt);
conn.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
centres.Add(new SelectListItem { Text = dt.Rows[i].ItemArray.GetValue(0).ToString(), Value = dt.Rows[i].ItemArray.GetValue(1).ToString() });
}
return Json(centres, JsonRequestBehavior.AllowGet);
}
Any ideas?