Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, March 1, 2018 8:26 PM
Hey Everyone!
So I have two dropdownlists, the second dropdown is dependent on the first one, hence the cascading style requirement. I have the first dropdownlist populated through a stored procedure but I'm unsure how to pass the ID value of the first dropdown to a stored procedure in order to populate the second drop down. I have the stored procedure for the second dropdown set up, but unsure how to call it within the controller with having the SelectedValue of the first dropdown being passed in as a parameter. Here's my code:
Controller:
public ActionResult CreateForm()
{
List<SelectListItem> CountyList = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("dbo.POPULATE_STATE", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
StateList.Add(new SelectListItem
{
Value = rdr[0].ToString(),
Text = rdr[1].ToString()
});
}
}
}
ViewBag.StateList = new SelectList(StateList.ToList(), "Value", "Text");
return View();
}
View:
<label for="ddlState">State</label>
@Html.DropDownList("ddlState", ViewBag.StateList as SelectList)
<label for="ddlCounty" >County</label>
@Html.DropDownList("ddlCounty", ViewBag.CountyList as SelectList)
Would appreciate any help on this, thanks!
All replies (7)
Friday, March 2, 2018 4:04 PM ✅Answered
I managed to get it working, basically the parameter of the dropdownlist selected value wasn't being passed to the controller. Here's the code that ended up working:
<script type="text/javascript">
$('#ddlCounty').change(function () {
var id = $('#ddlCounty').val();
$.ajax({url:'@Url.Action("TogetDistrictList")', data: ({ddlCounty: id}) } ).done(function(data){
$('#ddlDistrict').empty();
$.each(data,function(i,value){
$('#ddlDistrict').append( $('<option/>').val(value.Value).text(value.Text))
})
});
});
</script>
The sub menu is now being populated correctly, thanks for your help!
Friday, March 2, 2018 3:23 AM
<g class="gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="8" data-gr-id="8">Hi</g> <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="5" data-gr-id="5">rankone</g>,
Sir, I tested a working example for you, please refer to
public ActionResult CreateForm()
{
List< SelectListItem> StateList =new List<SelectListItem>();
List<SelectListItem> CountyList = new List<SelectListItem>();
//using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
//{
// con.Open();
// using (SqlCommand cmd = new SqlCommand("dbo.POPULATE_STATE", con))
// {
// cmd.CommandType = System.Data.CommandType.StoredProcedure;
// SqlDataReader rdr = cmd.ExecuteReader();
// while (rdr.Read())
// {
// StateList.Add(new SelectListItem
// {
// Value = rdr[0].ToString(),
// Text = rdr[1].ToString()
// });
// }
// }
//}
StateList.Add(new SelectListItem { Text = "1", Value = "1" });
StateList.Add(new SelectListItem { Text = "2", Value = "2" });
CountyList.Add(new SelectListItem { Text = "CountyList1", Value = "CountyList1" });
CountyList.Add(new SelectListItem { Text = "CountyList2", Value = "CountyList2" });
ViewBag.ddlState = new SelectList(StateList.ToList(), "Value", "Text");
ViewBag.ddlCounty = new SelectList(CountyList.ToList(), "Value", "Text");
return View();
}
public ActionResult TogetCountyList(string ddlState)
{
List<SelectListItem> CountyList = new List<SelectListItem>();
//using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
//{
// con.Open();
// using (SqlCommand cmd = new SqlCommand("dbo.POPULATE_STATE", con))
// {
// cmd.CommandType = System.Data.CommandType.StoredProcedure;
// SqlDataReader rdr = cmd.ExecuteReader();
// while (rdr.Read())
// {
// StateList.Add(new SelectListItem
// {
// Value = rdr[0].ToString(),
// Text = rdr[1].ToString()
// });
// }
// }
//}
CountyList.Add(new SelectListItem { Text = "CountyList1"+ ddlState, Value = "CountyList1" + ddlState });
CountyList.Add(new SelectListItem { Text = "CountyList2"+ ddlState, Value = "CountyList2"+ ddlState });
return Json(CountyList.ToList(),JsonRequestBehavior.AllowGet);
}
Then
@{
ViewBag.Title = "About";
}
<label for="ddlState">State</label>
@Html.DropDownList("ddlState" )
<label for="ddlCounty">County</label>
@Html.DropDownList("ddlCounty")
@section scripts{
<script type="text/javascript">
$('#ddlState').change(function(){
$.ajax('@Url.Action("TogetCountyList")', JSON.stringify({ddlState: $("#ddlState").val()}) ).done(function(data){
$('#ddlCounty').empty();
$.each(data,function(i,value){
$('#ddlCounty').append( $('<option/>').val(value.Value).text(value.Text))
})
});
});
With regards, Angelina Jolie
Friday, March 2, 2018 2:17 PM
Thanks for your reply, I'm still running into trouble as I am getting an NullReferenceException in the Json. I have altered the code to allow the data to be populated through a stored procedure instead of manually inserting values into the dropdownlist. Here's the updated code:
Controller:
public SqlCommand CreateCommand(string procedurename, SqlParameter[] parameters, SqlConnection connection)
{
SqlCommand cmd = new SqlCommand(procedurename, connection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter param in parameters)
{
if (param.Value == null)
param.Value = DBNull.Value;
cmd.Parameters.Add(param);
}
return cmd;
}
public ActionResult CreateForm()
{
List<SelectListItem> CountyList = new List<SelectListItem>();
List<SelectListItem> DistrictList = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("dbo.SELECT_COUNTY", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CountyList.Add(new SelectListItem
{
Value = rdr[0].ToString(),
Text = rdr[1].ToString()
});
}
}
}
ViewBag.CountyList = new SelectList(CountyList.ToList(), "Value", "Text");
return View();
}
public ActionResult TogetDistrictList(string CountyList)
{
List<SelectListItem> DistrictList = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
{
con.Open();
SqlParameter[] parameters = { new SqlParameter("@IDN_COUNTY", CountyList) };
SqlCommand cmd = CreateCommand("dbo.SELECT_DISTRICT", parameters, con);
//using (SqlCommand cmd = new SqlCommand("dbo.USP_SELECT_DISTRICT", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DistrictList.Add(new SelectListItem
{
Value = rdr[0].ToString(),
Text = rdr[1].ToString()
});
}
}
}
ViewBag.DistrictList = new SelectList(DistrictList.ToList(), "Value", "Text");
return Json(CountyList.ToList(), JsonRequestBehavior.AllowGet);
}
View:
<script type="text/javascript">
jQuery(function($){
$('#ddlCounty').change(function () {$.ajax('@Url.Action("TogetDistrictList")', JSON.stringify({CountyList: $("#ddlCounty").val()}) ).done(function(data){
$('#ddlDistrict').empty();
$.each(data,function(i,value){
$('#ddlDistrict').append($('<option/>').val(value.Value).text(value.Text))
})
});
});
});
</script>
@Html.DropDownList("ddlCounty", ViewBag.CountyList as SelectList})
@Html.DropDownList("ddlDistrict", Enumerable.Empty<SelectListItem>())
While debugging, I can see the CountyList parameter is null even after dropdown value is changed, this might be causing the issue. Any ideas ?
Friday, March 2, 2018 2:58 PM
Ok I basically narrowed the issue down to the parameter not being passed in as the selected value from the parent dropdown. Which is basically this line
SqlParameter[] parameters = { new SqlParameter("@IDN_COUNTY", CountyList) };
SqlCommand cmd = CreateCommand("dbo.SELECT_DISTRICT", parameters, con);
CountyList is NULL, so how do I get the selectedValue from the parent dropdownlist.
Friday, March 2, 2018 3:00 PM
Hi rankone,
Sorry that, I made a mistake before.
Please Change
$.ajax('@Url.Action("TogetCountyList")', JSON.stringify({ddlState: $("#ddlState").val()}) ).done(function(data){
To
$.ajax({'@Url.Action("TogetCountyList")', data: JSON.stringify({ddlState: $("#ddlState").val()}) } ).done(function(data){
Or
$.get('@Url.Action("TogetCountyList")',JSON.stringify({ddlState: $("#ddlState").val()}) , function(data){ …});
Then the ddlState will not be null;
With regards, Angelina Jolie
Friday, March 2, 2018 3:04 PM
$.ajax({url:'@Url.Action("TogetCountyList")', data: JSON.stringify({ddlState: $("#ddlState").val()}) } ).done(function(data){
Friday, March 2, 2018 3:22 PM
So this is what I have, but it looks like I have an extra parenthesis in there or maybe missing one ? Because I'm get an Expected ')' error.
$('#ddlCounty').change(function () {$.ajax('@Url.Action("TogetDistrictList")', data:JSON.stringify({ddlCounty: $("#ddlCounty").val()}) ).done(function(data){
$('#ddlDistrict').empty();
$.each(data,function(i,value){
$('#ddlDistrict').append($('<option/>').val(value.Value).text(value.Text))
})
});
});