I'm trying to update 2 dependent dropdowns simultaneously based on the value of the primary dropdown. Is it possible, if yes, what's wrong in my code? Correct, please.
Maybe it's better to use ASP.NET cascading dropdowns possibilites? If yes, how to do it with 3 dropdowns ?
View
#model RKB.Models.CountryStateViewModel
<br /><br/>
#using (Html.BeginForm("Index", "Home"))
{
<div class="container">
<div class="form-group">
#if (ViewBag.CountryList != null)
{
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "Выберите страну", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "Выберите штат", new { #class = "form-control" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.PriceId, new SelectList(" "), "Выберите цену", new { #class = "form-control", #style = "display:none" })
</div>
<button type="submit">Send</button>
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.PriceId + "'>" + row.Price1 + "</option>")
});
});
})
});
</script>
Controller
public class HomeController : Controller
{
RKBEntities db = new RKBEntities();
public ActionResult Index()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryStateViewModel csm)
{
return View();
}
public JsonResult GetStateList(int CountryId)
{
db.Configuration.ProxyCreationEnabled = false;
List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
return Json(StateList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPriceList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<Price> PriceList = db.Prices.Where(x => x.StateId == StateId).ToList();
return Json(PriceList, JsonRequestBehavior.AllowGet);
}
}
You have used the wrong property json, my friend.
For example: row.StateId => row.stateId.
Just try to modify following like this:
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.stateId + "'>" + row.stateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.priceId + "'>" + row.price1 + "</option>")
});
});
})
});
</script>
Hope to help, my friend :))
Related
I'm trying to use cascaded Drop Down for a project, but with a bit of a twist. For Power Users, they can enter a stock code and search. The retrieved information then updates the Parent Drop Down and the cascaded Drop Down selection.
Using a click event, I can search the entered value and it returns all the needed information. I can update the Parent to Display the correct information, But unable to get the child to display. It's stuck on showing " -- Select --" Populating the drop down's with data to select from works great. Could really use some insight and help.. Got myself stumped on the child. Thanks..
I followed this example to setup the Dropdowns. asp.net MVC cascading dropdown lists
<Controller>
public ActionResult Create()
{
ViewData["User"] = User.Identity.GetUserName();
BindPartType();
return View();
}
public void BindPartType()
{
partsmanagementEntities5 parttypelist = new partsmanagementEntities5(); //Parts
var parttype = parttypelist.parttypes.ToList();
List<SelectListItem> pli = new List<SelectListItem>();
pli.Add(new SelectListItem { Text = "--Select Catagory--", Value = "0" });
foreach (var m in parttype)
{
pli.Add(new SelectListItem { Text = m.PartType1, Value = m.idPartType.ToString() });
ViewBag.PartType = pli;
}
}
public JsonResult GetInventory(int? id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
var ddlpart = partlist.parts.Where(x => x.PartType == id).ToList();
List<SelectListItem> lipart = new List<SelectListItem>();
lipart.Add(new SelectListItem { Text = "--Select Inventory--", Value = "0" });
if (ddlpart != null)
{
foreach (var x in ddlpart)
{
lipart.Add(new SelectListItem { Text = x.PartDescription, Value = x.idParts.ToString() });
}
}
return Json(new SelectList(lipart, "Value", "Text", JsonRequestBehavior.AllowGet));
}
public JsonResult Check(string id)
{
partsmanagementEntities5 partlist = new partsmanagementEntities5();
StringBuilder test = new StringBuilder();
if(id != null && id != "")
{
foreach (char c in id)
{
if (!char.IsNumber(c))
test.Append(c);
}
var ddlpartnumber = partlist.parts.Where(x => x.PartNumber == id.ToString());
PartDetails li = new PartDetails();
foreach (var item in ddlpartnumber.ToList())
{
li.PartNumber = item.PartNumber;
li.PartPrice = item.PartPrice;
li.idParts = item.idParts;
li.EHF = item.EHF;
li.PartDescription = item.PartDescription;
li.PartImage = item.PartImage;
li.partImageContentType = item.partImageContentType;
li.unit = item.unit;
li.PartType = item.PartType;
li.VendorPartNumber = item.VendorPartNumber;
}
return Json(li, JsonRequestBehavior.AllowGet);
}
return Json("", JsonRequestBehavior.AllowGet);
}
<View>
<table>
<tr>
<td style="padding-left:0.8ex;padding-top:0.8ex">#Html.Label("Catagory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartType, ViewBag.PartType as List<SelectListItem>, new { style = "width: 800px;" })
#Html.ValidationMessageFor(model => model.PartType, "", new { #class = "text-danger" })
</td>
<td style="padding-left:6ex;padding-top:0.8ex"></td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Inventory: ")</td>
<td>
#Html.DropDownListFor(model => model.PartNumber, new SelectList(string.Empty, "Value", "Text"), "--Select Inventory--", new { style = "width:900px" })
#Html.ValidationMessageFor(model => model.PartNumber, "", new { #class = "text-danger" })
</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:6ex">#Html.Label("Or choose:")</td>
</tr>
<tr>
<td style="width:1px;white-space:nowrap;padding-left:0.8ex">#Html.Label("Enter Valid Part #: ")</td>
<td><input type="text" name="CheckPartNumber" id="CheckPartNumber"> <input type="button" id="Search" value="Search" class="btn btn-default" />
</tr>
</table>
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#PartType").change(function () {
$("#PartNumber").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetInventory", "partrequests")',
dataType: 'json',
data: { id: $("#PartType").val() },
success: function (PartNumber) {
$.each(PartNumber, function (i, PartNumber) {
$("#PartNumber").append('<option value="'
+ PartNumber.Value + '">'
+ PartNumber.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
$(document).ready(function () {
$("#Search").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("Check","partrequests")',
dataType: 'json',
data: { id: $("#CheckPartNumber").val() },
success: function (Data) {
var selectedValue = Data.PartType
$('#PartType option').map(function () {
if ($(this).val() == selectedValue) return this;
}).attr('selected', 'selected').change();
var selectedValue2 = Data.idParts;
$('#PartNumber option').map(function () {
if ($(this).val() == selectedValue2) return this;
}).attr('selected', 'selected');
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
I have a main view. Once the posting is done, it will render a partial view in the main view.
My partial view has a cascading dropdown list that changes the 2nd DropdownList items based on the selected value from the 1st DropdownList.
Here is my Dropdown in my Partial View.
#model MigratingDB.Models.ViewModel
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue1,
Model.DropdownViewModel.List1, "Select",htmlAttributes: new { #class = "form-control", #id = "ddl1" })
</div>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue2,
Model.DropdownViewModel.List2 = new SelectList(Enumerable.Empty<SelectListItem>()), "Select",
htmlAttributes: new { #class = "form-control", #id = "ddl2" })
</div>
The script I tried based from this.
<script>
$(function () {
$('#ddl1').change(function () {
$("#ddl2").empty();
var selectedValue = $(this).val();
$.ajax({
url: '#Url.Action("Getddl2Items", "Controller")',
type: "POST",
dataType: 'json',
data: { id: selectedValue },
success: function (value) {
$.each(value, function (i, val) {
$("#ddl2").append('<option value="' + val.Value + '">' +
val.Text + '</option>');
});
},
error: function (ex) {
alert('Failed' + ex);
},
});
});
});
</script>
In my Controller:
[HttpPost]
public ActionResult Foo (ViewModel vm)
{
// Dropdownlist
var list1 = // get items frop ddl1
vm.DropdownViewModel.List1= new SelectList(list1, "Value", "Text");
return PartialView("_PartialView", vm);
}
// Get ddl2 Items
public JsonResult Getddl2Items (int id)
{
var ViewModel = new ViewModel();
var list2= // get ddl2 items from the database
ViewModel.DropdownViewModel.List2= new SelectList(list2, "Value", "Text");
return Json(ViewModel.DropdownViewModel.List2, JsonRequestBehavior.AllowGet);
}
Every time I tried to select a value from the ddl1, it errors and show
Failed [object Object].
What causes this?
This is a long post that I tested and works. Since it is long, you can pick out the parts you need. Let's work together to figure out why it is not working for you.
This will be your table and data creation:
--Use your database name instead of Breaz
USE [Breaz]
GO
/****** Object: Table [dbo].[tblCity] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblCity](
[Cityid] [int] NOT NULL,
[CityName] [nvarchar](50) NULL,
[stateid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[tblState] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblState](
[stateid] [int] NOT NULL,
[statename] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[stateid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (1, N'Phoenix', 1)
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (2, N'Las Angeles', 2)
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (1, N'Arizona')
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (2, N'California')
ALTER TABLE [dbo].[tblCity] WITH CHECK ADD FOREIGN KEY([stateid])
REFERENCES [dbo].[tblState] ([stateid])
GO
Create your edmx, by going through visual studio wizard.
Create your view model:
//user your namespace
namespace Testy20161006.Models
{
public class Registration
{
[Required(ErrorMessage = "Enter State")]
public string State { get; set; }
[Required(ErrorMessage = "Enter City")]
public string City { get; set; }
}
}
Your controller/classes:
public class HomeController : Controller
{
public JsonResult getCity(int id)
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == id).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
licities.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
return Json(new SelectList(licities, "Value", "Text", JsonRequestBehavior.AllowGet));
}
}
[HttpPost]
public ActionResult IndexStackOverflow(Registration registration)
{
//put breakpoint here to see values coming back from view
return View(registration);
}
//use your name of action that starts the process, named in routeconfig.cs
public ActionResult IndexStackOverflow()
{
bindState();
return View();
}
public void bindState()
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var state = objEF.tblStates.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
foreach (var m in state)
{
li.Add(new SelectListItem { Text = m.statename, Value = m.stateid.ToString() });
ViewBag.state = li;
}
}
}
Here is your view:
#model Testy20161006.Models.Registration
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getcity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
#using (Html.BeginForm())
{
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div><input type="button" value="submit" /></div>
}
</body>
</html>
Here is an example that returns Json value from a SelectListItem in a ViewModel.
public class ReturnJsonVM
{
public List<SelectListItem> licities = new List<SelectListItem>();
}
public class HomeController : Controller
{
//use your name of action that starts the process, named in routeconfig.cs
public string IndexStackOverflow()
{
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == 1).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
ReturnJsonVM returnJsonVM = new ReturnJsonVM();
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
returnJsonVM.licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
string json = JsonConvert.SerializeObject(returnJsonVM.licities);
//put your break point here to see example that return Json value from SelectListItem in ViewModel
return json;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a problem filtering information in a second dropdown, that information should depend on the first selection of the first dropdown, I would like to know how I can filter that information
This is my code:
c# Controller:
[HttpGet]
public IActionResult SubTrails()
{
try
{
var n = _unitOfWork.SubTrails.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
[HttpGet]
public IActionResult Levels()
{
try
{
var n = _unitOfWork.Levels.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
[HttpGet]
public IActionResult Trails()
{
try
{
var n = _unitOfWork.Trails.GetAll().ToList();
if (n == null)
{
return NoContent();
}
return new ObjectResult(n);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Internal Server Error" });
}
}
cshtml:
#model DefinityFirst.Mobile.Admin.Web.Services.Marvel.Contracts.ListTrailSubTrailLevelContract
#inject DefinityFirst.Mobile.Admin.Web.Services.Marvel.IMarvelServices DropDownDataHelper
#{
ViewBag.Title = "Create";
}#if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> #Html.ValidationMessage("Error")
</div>
}
<h2>Create</h2>
<p>New TrailSubTRailLEvel</p>
#using (Html.BeginForm("TrailSubTrailLevel", "TrailSubTrailLevel", FormMethod.Post, new { id = "demoForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Trail</h4>
<div class="form-group">
#Html.Label("", "Trail", new { #class = "control-label col-md-2" })
<div class="col-md-10" id = "partialDiv">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.TrailId, await DropDownDataHelper.GetTrailsDdl(), "Select one", new { #class = "form-control", onchange = "SelectedIndexChanged()" })
#Html.ValidationMessageFor(model => model.TrailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("", "SubTrail", new { #class = "control-label col-md-2", #name = "Subtrail", #id= "Subtrail" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.SubtrailId, await DropDownDataHelper.SubTrailDdl(), "Select one", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SubtrailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("", "Level", new { #class = "control-label col-md-2", #name = "Level", #id = "Level" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TrailContract.Responsable.Id, Model.ManagersList, "Select one", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.LevelId, await DropDownDataHelper.LevelsDdl(), "Select one", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.LevelId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script type="text/javascript">
$('#SubtrailId').hide();
$('#LevelId').hide();
$("#Subtrail").hide();
$("#Level").hide();
$('#TrailId').on('change', function () {
// alert("este valor es de trail", this.value)
if (this.value != 0) {
$("#Subtrail").show();
$('#SubtrailId').show();
alert(this.value)
} else {
$('#SubtrailId').hide();
$('#LevelId').hide();
// alert("no es diferente ")
}
})
$('#SubtrailId').on('change', function () {
//alert("este valor es de subtrail", this.value)
if (this.value != 0) {
$("#Level").show();
$('#LevelId').show();
//alert(this.value)
} else {
$('#LevelId').hide();
// alert("no es diferente ")
}
})
function SelectedIndexChanged() {
//Form post
//alert("esta validacion jala", this.value)
document.demoForm.submit();
}
</script>
}
But when I enter the view loads all the data only once and when you change options in the dropdown does not reload dataView
I have implemented cascading dropdowns in my project using unobtrusive ajax
This example is a country list populated on the server (state is also populated if country is already selected). If the country dropdown selection is changed the state list dropdown updates by ajax
CompanyInfoViewModel has these properties (some left out for brevity)
public IList<SelectListItem> AvailableCountries { get; set; }
public string CompanyCountry { get; set; } = string.Empty;
public IList<SelectListItem> AvailableStates { get; set; }
[StringLength(200, ErrorMessage = "State/Region has a maximum length of 200 characters")]
public string CompanyRegion { get; set; } = string.Empty;
In the controller I populate the initial data
var model = new CompanyInfoViewModel();
model.CompanyRegion = selectedSite.CompanyRegion;
model.CompanyCountry = selectedSite.CompanyCountry;
model.AvailableCountries.Add(new SelectListItem { Text = sr["-Please select-"], Value = "" });
var countries = await geoDataManager.GetAllCountries();
var selectedCountryGuid = Guid.Empty;
foreach (var country in countries)
{
if (country.ISOCode2 == model.CompanyCountry)
{
selectedCountryGuid = country.Id;
}
model.AvailableCountries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.ISOCode2.ToString()
});
}
if (selectedCountryGuid != Guid.Empty)
{
var states = await geoDataManager.GetGeoZonesByCountry(selectedCountryGuid);
foreach (var state in states)
{
model.AvailableStates.Add(new SelectListItem()
{
Text = state.Name,
Value = state.Code
});
}
}
Requires jquery unobtrusive ajax
This is my custom unobtrusivecascade script:
$(function () {
var $elems = $('select[data-cascade-childof]');
if ($elems) {
$elems.each(function (index, ele) {
var $parent = $('#' + $(ele).data('cascade-childof'));
var serviceUrl = $(ele).data('cascade-serviceurl');
var origVal = $(ele).data('cascade-orig-val');
var selectLabel = $(ele).data('cascade-select-label');
var disableOnEmptyParent = $(ele).data('cascade-disableonemptyparent');
var emptyParentValue = $(ele).data('cascade-parent-emptyvalue');
$parent.change(function () {
$.getJSON(serviceUrl + $parent.val(), function (data) {
var items = '<option>' + selectLabel + '</option>';
$.each(data, function (i, item) {
items += "<option value='" + item.value + "'>" + item.text + "</option>";
});
$(ele).html(items);
if (origVal.length > 0) {
var found = $(ele).find("option[value=" + origVal + "]").length > 0;
if (found) {
$(ele).val(origVal);
}
}
});
if (disableOnEmptyParent) {
var emptyParent = ($parent.val() === emptyParentValue);
if (emptyParent) {
$(ele).prop("disabled", true);
}
else {
$(ele).prop("disabled", false);
}
}
});
});
}
});
The markup in the view is like this:
<div class="form-group">
<label asp-for="CompanyCountry" class="col-md-2 control-label">#sr["Country"]</label>
<div class="col-md-10">
<select id="CompanyCountry" asp-for="CompanyCountry"
asp-items="Model.AvailableCountries" class="form-control"></select>
<span asp-validation-for="CompanyCountry" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="CompanyRegion" class="col-md-2 control-label">#sr["State"]</label>
<div class="col-md-10">
<select id="CompanyRegion" class="form-control"
asp-for="CompanyRegion"
asp-items="Model.AvailableStates"
data-cascade-childof="CompanyCountry"
data-cascade-serviceurl='#Url.Content("~/CoreData/GetStatesJson/?countryCode=")'
data-cascade-orig-val="#Model.CompanyRegion"
data-cascade-select-label="-Please select-"></select>
<span asp-validation-for="CompanyRegion" class="text-danger"></span>
</div>
</div>
Another controller is used to return the json data for the state list based on the selected country
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> GetStatesJson(
string countryCode)
{
var country = await dataManager.FetchCountry(countryCode);
List<IGeoZone> states;
if (country != null)
{
states = await dataManager.GetGeoZonesByCountry(country.Id);
}
else
{
states = new List<IGeoZone>(); //empty list
}
var selecteList = new SelectList(states, "Code", "Name");
return Json(selecteList);
}
In this MVC application I've created cascading dropdown list i.e it will first populate countries list and after selecting country jquery's onchange event is called which will fetch the further states from the controller which further gets those data by edmx entity model in database.i have used ajax request to call the JSON method in this.After selecting states the new dropdown list would get activated for selecting Cities.Whenever I select countries from the drop down an alertbox pops out and says states retrieving failed.[object][object] also I didn't create relationship between tables as foreign key is that necessary
Location Controller:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
TestDBEntities db = new TestDBEntities();
ViewBag.Country = new SelectList(db.tblCountries, "CountryID", "CountryName");
return View();
}
public JsonResult GetState(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstatevalue(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.StateID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public IList<tblState> Getstatevalue(int CountryId)
{
TestDBEntities db = new TestDBEntities();
return db.tblStates.Where(m => m.CountryID == CountryId).ToList();
}
public JsonResult GetCity(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var cityList = this.Getcityvalue(Convert.ToInt32(id));
var cityData = cityList.Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
public IList<tblCity> Getcityvalue(int StateId)
{
TestDBEntities db = new TestDBEntities();
return db.tblCities.Where(m => m.StateID == StateId).ToList();
}
}
}
Index.cshtml view
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeData</legend>
<div class="editor-label">
#Html.Label("Country")<br />
</div>
<div>
#Html.DropDownList("Country", ViewBag.Country as SelectList, "-- Please Select a Country --", new { style = "width:150px", #id = "Country" })
</div>
<div class="editor-label">
<br />
#Html.Label("State")<br />
</div>
<div>
#Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "-- Please select a State --",
new { style = "width:150px", #class = "dropdown1" })
</div>
<div class="editor-label">
<br />
#Html.Label("City")<br />
</div>
<div>
#Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), "-- Please select a city --",
new { style = "width:150px", #class = "dropdown2", #id = "City" })
</div>
<p>
<input type="button" onclick="ddlInsert()" value="Submit" />
</p>
</fieldset>
}
javascript code :
<script type="text/javascript">
$(document).ready(function () {
// this is Country Dropdown Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("Getstates")', // here we are Calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert(' states retrieving fail.' + ex);
}
});
return false;
})
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCities")', // here we are Calling json method
dataType: 'json',
data: { id: $("#State").val() },
// Get Selected Country ID.
success: function (cities) {
$.each(cities, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert(' city retrieving fail.' + ex);
}
});
return false;
})
});
</script>
When I select a country in it No state gets loaded or populated into the dropdown list for states.
My Create view was like this:
#model ContactProject.Models.Activity.Activity
#{
ViewBag.Title = "Create";
IEnumerable<ContactProject.Models.Activity.Activity> activities = ViewBag.Activities;
}
<div class="editor-label">
#Html.Label("Project")
</div>
<div class="editor-field">
#Html.DropDownList("Projects", ViewBag.Project as SelectList,"----Project----", new { id = "ProjectsID" })
#Html.ValidationMessageFor(model => model.iProjectID)
</div>
<div class="editor-label">
#Html.Label("Title")
</div>
<div class="editor-field" id="TitlesDivID">
<select id="TitlesID" name="Titles"></select>
</div>
// other codes...
if (activities !=null){
// Display activities.
}
here is the code of my JS
$('#ProjectsID').change(function () {
var URL = 'TitleList';
$.getJSON(URL + '/' + $('#ProjectsID').val(), function (data) {
var items = '<option>Select a Title</option>';
$.each(data, function (i, title) {
items += "<option value='" + title.Value + "'>" + title.Text + "</option>";
if (items != null)
{
var addValue = $('#ProjectsID').val();
$.ajax
({
type: "POST",
url: "/Activity/getCreateActivities",
data: { projectID: addValue },
success: function (#ViewBag.Activities) {
}
})
}
})
basically I want to implement my function with this JS to display not only of title related to the project but also all the activities has the same project name.
That's why I'm writing "success: function (#ViewBag.Activities) in my jquery call back function."
here is the method in my controller:
public ActionResult getCreateActivities(string projectID)
{
int iProjectID = Int32.Parse(projectID);
ViewBag.Project = GetProjects();
var Activities = (from a in db.Activities
where a.iProjectID == iProjectID
select a).ToList();
ViewBag.Activities = Activities;
return View("Create");
}
but when I am using breakpoint to debug, there are #ViewBag.Activities returned with value and counts, but seems like didn't display on my screen, anyone has any thoughts on that? any contribute will be greatly appreciated.
Update:
<table>
#foreach (var item in Activities) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProjectID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Project.ProjectName)
</td>
</tr>
If you set some values in ViewBag with an ajax request, you won't get it. The rite way to handle this is, simply return the data in JSON format and access it.
public ActionResult getCreateActivities(string projectID)
{
int iProjectID = Int32.Parse(projectID);
var Activities = (from a in db.Activities
where a.iProjectID == iProjectID
select a).ToList();
return Json(new { Projects : GetProjects(),
Activities : Activities } ,JsonRequestBehaviour.AllowGet);
}
The above will return a JSON representation of an anonymous object like this
{
"Projects": [ { "Id": 2 } ],
"Activities": [ { "id": 113,"Name": "My name" } ]
}
And in your ajax method's success callback, access it like
success(function(data){
// now you can acceess data.Projects and data.Activities
}