Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have two dropdowns for Country and City.
HTML
<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>
<div class="editor-label">
@Html.LabelFor(model => model.City, "City")
</div>
<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)
</div>

and the javascript function
JavaScript
<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.empty();
// select.append($('<option/>',{ value: 0, text: "Select Major" }));
$.each(CountryData, function (index,itemData) { //
select.append($('<option/>', { value: itemData.value, text: itemData.Text }));
});
});
});
});
</script>

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
Posted
v3
Comments
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

[HttpPost]
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...
post-and-get-in-mvc-razor-jquery.html[^]
 
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