Click here to Skip to main content
15,610,483 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have two dropdowns for Country and City.
<div class="editor-field">
@Html.DropDownListFor(Model => Model.Country, new SelectList(ViewBag.Countries as System.Collections.IEnumerable, "CountryCode", "CountryName"), "Select country", new { id = "ddlCountry" })
@Html.ValidationMessageFor(model => model.Country)
<div class="editor-label">
@Html.LabelFor(model => model.City, "City")
<div class="editor-field">
@Html.DropDownListFor(Model => Model.City, new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"), "select a city", new { id = "ddlCity" })
@Html.ValidationMessageFor(model => model.City)

and the javascript function
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCountry").change(function () {
var idCity = $(this).val();
$.getJSON("/Applicant/GetCityByCountry", { id: idCity },
function (CountryData) {
var select = $("#ddlCity");
// select.append($('<option/>',{ value: 0, text: "Select Major" }));
$.each(CountryData, function (index,itemData) { //
select.append($('<option/>', { value: itemData.value, text: itemData.Text }));

When I select a country, it populates the city dropdown, but when I am trying to insert, it gives error.

The INSERT statement conflicted with the FOREIGN KEY constraint "Applicant_City". The conflict occurred in database "EngageDBase", table "dbo.City", column 'CityId'.
The statement has been terminated.

Quick watch is always showing countrycode and cityid equal to '0' which is not in city table.
Country and city model are null in the view.

Don't know what to do please help.

[Code] block Edited
Karthik. A 16-Jul-12 14:56pm    
For the action method that handles the http post, see if the name of the drop down lists (in the html generated) matches.

That is:

Assuming the Html.DropDownList generates a select with name as "Country" and "City" (seeing the page's html would give you the exact value, but from prop. name looks like its what I've said), your action method should be

public ActionResult PostAction(string Country, string City)

If you could also post the code for your controller one of us could exactly pin-point the issue!

1 solution

Cascading dropdown implementation here...
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900