Can anyone help me. My code is not working this is cascading drop down list.
It's connected to my database.
Jquery Code:
<script type="text/javascript">
$(document).ready(function () {
$("#SiteId").change(function () {
var idDept = $(this).val();
$.getJSON("Service/GetBuildingNameList", { id: idDept },
function (myData) {
var select = $("#BuildingID");
select.empty();
$.each(myData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
</script>
@Html.DropDownListFor(model => model.SiteId, new SelectList(ViewBag.ListSiteClass as System.Collections.IEnumerable, "SiteId", "SiteName"),
"", new { id = "SiteId" })
@Html.DropDownListFor(model => model.BuildingId,
new SelectList(Enumerable.Empty<SelectListItem>(), "BuildingID", "BuildingName"), "",
new { id = "BuildingID" })
Controller Code:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetBuildingNameList(int id)
{
var buildingnamelist = BuildingDAO.GetBuildingNameList(id);
var myData = buildingnamelist.Select(a => new SelectListItem()
{
Text = a.BuildingName,
Value = a.BuildingId.ToString(),
});
return Json(myData, JsonRequestBehavior.AllowGet);
}
BuildingDAO.GetBuildingNameList Code:
public class BuildingDAO
{
public static string connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
public static List<BuildingDTO> GetBuildingNameList(int id)
{
using (SqlConnection objcon = new SqlConnection(connectionString))
{
objcon.Open();
using (SqlCommand cmd = new SqlCommand("sp_Building", objcon) { CommandType = CommandType.StoredProcedure })
{
cmd.Parameters.AddWithValue("Action", "GetBuildingList");
cmd.Parameters.AddWithValue("BuildingId", "");
cmd.Parameters.AddWithValue("BuildingName", "");
cmd.Parameters.AddWithValue("BuildingManagerID", "");
cmd.Parameters.AddWithValue("SiteId", id);
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable table = new DataTable();
table.Load(reader);
List<BuildingDTO> LSBuildingList = new List<BuildingDTO>();
foreach (DataRow row in table.Rows)
{
BuildingDTO ms = new BuildingDTO();
ms.BuildingId = Convert.ToInt32(row["BuildingID"].ToString());
ms.BuildingName = row["BuildingName"].ToString();
ms.SiteId = Convert.ToInt32(row["SiteID"].ToString());
LSBuildingList.Add(ms);
}
return LSBuildingList;
}
}
}
}
}
I want to get the value of SiteId and pass it to my controller.
For example SiteId = 1. The BuildingID must be a list of Siteid that is equal to 1.