Reputation: 15866
view
<script type="text/javascript">
function getCities(abbr) {
$.ajax({
url: '@Url.Action("SayaclariGetir", "Enerji")',
data: { abbreviation: abbr },
dataType: "json",
type: "POST",
error: function () {
alert("Error!");
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.sno + "\">" + item.seri_no + "</option>";
});
$("#sayaclar").html(items);
}
});
}
$(document).ready(function () {
$("#musteriler").change(function () {
var abbr = $("#musteriler").val();
getCities(abbr);
});
});
</script>
<div>
<table>
<tbody>
<tr>
<td>@Html.DropDownListFor(x => x.musteri_id, new SelectList(Model.musteriler, "sno", "musteri_adi"), "-- Müşteri Seçiniz --", new { id = "musteriler" })
</td>
<td>@Html.DropDownListFor(x => x.sayac_id, new SelectList(Model.sayaclar, "sno", "seri_no"), "-- Sayaç Seçiniz --", new { id = "sayaclar" })
</td>
<td>
<input type="submit" value="Kaydet" />
</td>
</tr>
</tbody>
</table>
</div>
controller
[HttpPost]
public ActionResult SayaclariGetir(string abbreviation)
{
int musteri_id = Int32.Parse(abbreviation);
IEnumerable<TblSayaclar> _sayaclar = entity.TblSayaclar.Where(x => x.musteri_id == musteri_id);
return new JsonResult
{
Data = new
{
success = true,
sayaclar = _sayaclar
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
model
public class TuketimRaporViewModel
{
public IEnumerable<TblMusteriler> musteriler { get; set; }
public IEnumerable<TblSayaclar> sayaclar { get; set; }
public int musteri_id { get; set; }
public int sayac_id { get; set; }
}
When first dropdown changed I get the alert "Error!".I cant find, Why I get alert message?
EDIT
When I write this sayaclar = new SelectList(_sayaclar,"sno","seri_no")
instead of sayaclar = _sayaclar
not error ocurred but,this time, second dropdownlist values are "undefined".
Thanks.
Upvotes: 2
Views: 3891
Reputation: 53
you could use the AjaxDropdown from here: http://awesome.codeplex.com
it has a demo here: http://demo.aspnetawesome.com/AjaxDropdownDemo
Upvotes: 2
Reputation: 15866
I wrote this and it works:
[HttpPost]
public ActionResult SayaclariGetir(string abbreviation)
{
int musteri_id = Int32.Parse(abbreviation);
var _sayaclar = entity.TblSayaclar.Where(x => x.musteri_id == musteri_id).Select(x => new { sno = x.sno, seri_no = x.seri_no });
return Json(_sayaclar, JsonRequestBehavior.AllowGet);
}
Upvotes: 2