--------Razor-------
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Address</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Address1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address1)
@Html.ValidationMessageFor(model => model.Address1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.countryid, "Country")
</div>
<div class="editor-field">
@Html.DropDownList("countryid", String.Empty)
@Html.ValidationMessageFor(model => model.countryid)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.stateid, "State")
</div>
<div class="editor-field">
@Html.DropDownList("stateid", String.Empty)
@Html.ValidationMessageFor(model => model.stateid)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.cityid, "City")
</div>
<div class="editor-field">
@Html.DropDownList("cityid", String.Empty)
@Html.ValidationMessageFor(model => model.cityid)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.zipcode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.zipcode)
@Html.ValidationMessageFor(model => model.zipcode)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@*@section Scripts {
@Scripts.Render("~/bundles/jqueryval")*@
---------JSON---------------
<script type="text/javascript">
$(document).ready(function ()
{
//Dropdownlist Selectedchange event
$("#countryid").change(function ()
{
$("#stateid").empty();
$.ajax({
type:'POST',
url: '@Url.Action("SelectStates")',
dataType: 'json',
data: { id: $("#countryid").val() },
success: function (states)
{
$.each(states, function (i, state)
{
$("#stateid").append('<option value="'
+ state.id + '">'
+ state.state1 + '</option>');
});
$("#stateid").change();
},
error: function (ex)
{
alert('Failed to retrieve states.' + ex.responseText);
}
});
return false;
})
$("#stateid").change(function () {
$("#cityid").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("SelectCities")',
dataType: 'json',
data: { id: $("#stateid").val() },
success: function (cities) {
$.each(cities, function (i, cities) {
$("#cityid").append('<option value="'
+ cities.Id + '">'
+ cities.city1 + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve Cities.' + ex.responseText);
}
});
return false;
})
});
</script>
--------Controller-----------------
public JsonResult SelectStates(int id)
{
db.Configuration.ProxyCreationEnabled = false;
IEnumerable<State> states = db.States.Where(stat => stat.Countryid == id);
return Json(states);
}
public JsonResult SelectCities(int id)
{
db.Configuration.ProxyCreationEnabled = false;
IEnumerable<City> cities = db.Cities.Where(city => city.stateid == id);
return Json(cities);
}
--------------------------------------------------------------------------------------------------------------------------------------