Friday, June 11, 2010

JSON Calling from MVC Page

HTML:

<%= Html.DropDownList("", new SelectList(ViewData["States"] as IEnumerable, "Id", "Name", Model))%>
<%= Html.DropDownList("", new SelectList(ViewData["Cities"] as IEnumerable, "Id", "Name", Model))%>


Javascript:

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("select[id='StateId']").change(function() {
$.ajax({
type: "POST",
url: "/Supplier/StateCityInfo/",
data: { StateId: $(this).val() },
dataType: "json",
error: function(xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
alert(status);
},
success: function(data) {
$("#CityId").empty();
$.each(data, function(key, City) {
$("#CityId").append($("<option></option>").val(City.Id).html(City.Name));
});
}
});
})
})
</script>


Supplier Controller:

public class SupplierController : Controller
{
[AcceptVerbs("POST")]
public ActionResult StateCityInfo(int StateId)
{
return Json(this.AllCity(StateId));
}
}

No comments: