I want to cascade multiple Dropdown lists using mvc 4 razor in ASP.NET - javascript

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.

Related

Cascaded Drop Down List with search box

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>

Populate Dynamic DropDownListFor in Javascript

I have a couple of drop down lists... The first of which has an onchange event that calls a Javascript funcction:
#for (int i = 0; i < Model.things.Count; i++)
{
<tr>
<td>
#Html.DropDownListFor(m => m.Category[i].ID, ViewBag.Category as SelectList, "Please select a Category", new { #class = "class1", onchange = "Changed(this)" })
</td>
<td>
#Html.DropDownListFor(m => m.SubCategory[i].ID, Enumerable.Empty<SelectListItem>(), "Please select a Sub Category", new { #class = "class2" })
</td>
</tr>
}
Within this function I am making an ajax call to a controller method that returns a SelectList:
function TrackerChanged(val) {
var id = val.value;
$j.ajax({
url: appRoot + 'Controller/Method',
type: 'post',
data: { 'id': id},
success: function (results) {
if (results) {
**** POPULATE SECOND DROPDOWN ABOVE ***
}
else {
alert("Error updating comment");
}
},
failure: function () {
alert("Error updating comment");
}
});
}
The Controller Method returns a SelectList:
public SelectList Method(id categoryID)
{
IEnumerable<SelectListItem> select = null;
// Populate the IEnumerable with SubCategory results to show in the second Drop Down
return new SelectList(select, "Value", "Text");
}
but as you may notice from the comment in my ajax success chunk - I do not know how I would bind my new results back to the controller.
Please can someone help. I have looked for some examples and nothing seems to be working for me.

Cascading dropdown list does not bind data to the 2nd dropdown

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;
}
}

Mvc Ajax post from check-boxes in partial view

I have a partial view which is used to show a checkbox in a column of table in razor. When I click on any checkbox in the table its posting back to controller with Id of first row and not the Id of row in which the check-box is contained. The javascript function to post ajax request is "SaveChanges" as given below.
The hidden field "RecurrenceScheduleId" is the primary key id.
Am I doing something wrong here?
- Following are my view & controller action:
#model SMRDS.Model.RecurrenceSchedule
#using (Ajax.BeginForm("_LogOccurancePartial", "Schedule",
new AjaxOptions
{
UpdateTargetId = "tdOccurance",
HttpMethod = "post",
LoadingElementId = "btnProgress",
OnBegin = "dialogBegin",
OnSuccess = "updateSuccess",
OnFailure = "dialogFailure"
},
new { id = "frm-toggle" }))
{
#Html.HiddenFor(model => model.RecurrenceScheduleId)
#Html.CheckBoxFor(m => m.LogOccurences, new { #onclick ="SaveChanges(this)" })
}
<script>
function updateSuccess() {}
function dialogFailure() {}
function dialogComplete() {}
function dialogBegin() {}
function SaveChanges(checkboxInput) {
$.ajax({
type: 'POST',
url: '/Schedule/_LogOccurancePartial',
data: { newValue: checkboxInput.checked, id: $("#RecurrenceScheduleId").val() },
dataType: 'json',
success: function (response) {
//handle success
}
});
}
Controller Action :
public JsonResult _LogOccurancePartial(bool newValue,int id)
{
var result = BLL.Service.RecurrenceSchedules.UpdateLogOccurence(id, newValue);
return Json(new { result = result }, JsonRequestBehavior.AllowGet);
}
Update
Following is the html rendered for hidden fields. At present I have only two rows with Ids "40" & "41".
<input data-val="true" id="RecurrenceScheduleId"
name="RecurrenceScheduleId" type="hidden" value="40">
<input data-val="true" id="RecurrenceScheduleId"
name="RecurrenceScheduleId" type="hidden" value="41">
It is your responsibility to maintain unique ids when you use the helpers.
If you had a model
public class ViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
And your view contains a collection you can use a for loop with an index to override the id with unique values.
#model List<ViewModel>
#for(int i = 0; i < Model.Count(); i++)
{
#Html.HiddenFor(m => Model[i].Id, htmlAttributes: new { id = "item" + item.Id })
}
But you can also adjust your click handler so you don't need to find a hidden input by id.
#Html.CheckBoxFor(m => m.LogOccurences,
new { #class="trigger", data_rsid=m.RecurrenceScheduleId })
<script>
$("body").on("click", ".trigger", function(e) {
var rsId = $(this).data("rsid");
var checked = $(this).prop("checked");
var data = { newValue: checked, id: rsId }
$.ajax({ ... });
});
</script>

Cascading drop down list (SubLocality) not working in asp.net mvc

I have three dropdown List.The First action method for City drop down is as---
public ActionResult Create()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select your City", Value = "----" });
li.Add(new SelectListItem { Text = "Faridabaad", Value = "Faridabaad" });
li.Add(new SelectListItem { Text = "Greater Noida", Value = "Greater Noida" });
li.Add(new SelectListItem { Text = "Gurgaon", Value = "Gurgaon" });
li.Add(new SelectListItem { Text = "Noida", Value = "Noida" });
li.Add(new SelectListItem { Text = "New Delhi", Value = "New Delhi" });
ViewData["City"] = li;
return View();
}
then i have action method for my Locality drop down list which changes as we change city name like this------
public JsonResult LoadLocalities(string id)
{
List<SelectListItem> localities = new List<SelectListItem>();
switch(id)
{
case"New Delhi":
localities.Add(new SelectListItem { Text = "Select your locality", Value = "0" });
localities.Add(new SelectListItem{ Text ="East Delhi", Value = "1" });
localities.Add(new SelectListItem{ Text ="West Delhi", Value = "2" });
localities.Add(new SelectListItem{ Text ="North Delhi", Value = "3" });
localities.Add(new SelectListItem { Text = "South Delhi", Value = "4" });
break;
}
return Json(new SelectList(localities, "Value", "Text"));
}
and the action method for the last sub locality drop down which changes with the change in locality name is like this---
public JsonResult LoadSubLocalities(string id)
{
List<SelectListItem> sublocalities = new List<SelectListItem>();
switch (id)
{
case"1":
sublocalities.Add(new SelectListItem { Text = "Select your sublocality", Value = "0" });
sublocalities.Add(new SelectListItem { Text = "Region1", Value = "1" });
sublocalities.Add(new SelectListItem { Text = "Region2", Value = "2" });
break;
}
return Json(new SelectList(sublocalities, "Value", "Text"));
}
now the view page is something like this------
<!DOCTYPE html>
<head>
<title></title>
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<body>
<div id="map_canvas" style="width: 800px; height: 700px; float:left"></div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Enter the Project Details</legend>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#if (ViewData.ContainsKey("City")){
#Html.DropDownListFor(model => model.City, ViewData["City"] as List<SelectListItem>, new { style = "width:250px", #class = "DropDown1"})
#Html.ValidationMessageFor(model => model.City)
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Locality)
</div>
<div class="editor-field">
#Html.DropDownList("Locality", new SelectList(string.Empty,"Value","Text"),"Please Select a locality", new { style = "width:250px", #class = "DropDown1" })
#Html.ValidationMessageFor(model => model.Locality)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SubLocality)
</div>
<div class="editor-field">
#Html.DropDownList("SubLocality", new SelectList(string.Empty, "Value", "Text"), "Please Select a sub locality", new { style = "width:250px", #class = "DropDown1" })
#Html.ValidationMessageFor(model => model.SubLocality)
</div>
<p>
<input type="submit" value="Save Project" />
</p>
</fieldset>
Now my javaScript code is something like this where i have written code to fetch city from controller then change locality as the city name changes and change sub locality name with change in locality name-----
<script type="text/javascript">
$(document).ready(function () {
$("#City").change(function () {
$("#Locality").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadLocalities","Project")',
dataType: 'json',
data: { id: $("#City").val() },
success: function (localities) {
$.each(localities, function (i, locality) {
$("#Locality").append('<option value="' + locality.Value + '">' +
locality.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retreive Locality.' + ex);
}
});
return false;
})
$("#Locality").change(function () {
$("#SubLocality").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadSubLocalities")',
dataType: 'Json',
data: { id: $("Locality").val() },
success: function (sublocalities) {
$.each(sublocalities, function (i, sublocality) {
$("#SubLocality").append('<option value="' + sublocality.Value + '">' +
sublocality.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve SubLocality.' + ex);
}
});
return false;
})
});
</script>
}
Now, My problem is that my Locality is working fine with change in city name but SubLocality drop down is not working with change in locality name---
The reason your $("#Locality").change(function () { is not working is because the following line
data: { id: $("Locality").val() },
return undefined. It needs to be
data: { id: $("#Locality").val() }, // add hash
however the correct approach is to use
data: { id: $(this).val() },
in order to avoid traversing the DOM again to get the element with id="Locality"
There are numerous other issues with your code, particularly in respect to validation and returning the view if ModelState is invalid
When generating List<SelectListItem>, do not add the label option
(i.e. sublocalities.Add(new SelectListItem { Text = "Select your
sublocality", Value = "0" });). You are giving the label option a
value which means that its always valid. As it currently is, you may
as well delete the #Html.ValidationMessageFor() associated with
each dropdown.
Never give the SelectList the same name as the property your
binding to (in your case City)
In your LoadLocalities() and LoadSubLocalities() methods you
first create List<SelectListItem> and then create a new
SelectList (which is IEnumerable<SelectListItem>) so its just
unnecessary extra overhead. In any case the client has no knowledge
of what a C# class is and you just returning twice as much data
across the wire as is necessary (the Selected,Disabled and
Group properties which you never use). Instead just pass back a
collection of anonymous objects containing 2 properties (for the
option value and text)

Categories

Resources