MVC 5嵌套下拉列表(县城)不会过滤第二个下拉列表

时间:2015-10-22 22:25:15

标签: asp.net-mvc asp.net-mvc-5

我可以从数据库中获取县和镇。但是当我从第一个下拉列表中选择县时,第二个不会根据第一个下载过滤。当ajax运行时,它会直接跳错误。然后它会给出“Hata”#39 ; alert.Following代码来自控制器。

public class AfetGirisController : Controller
{
    //
    // GET: /AfetGiris/
    MVCAfetGirisContext db = new MVCAfetGirisContext();

    public ActionResult YeniKayit()
    {

        //ViewBag.iller = new SelectList(db.Ils.ToList(), "IlId", "IlAd");
        List<string> iller= new List<string>();
        ViewBag.iller = new SelectList(db.Ils.ToList(), "IlId", "IlAd");
        List<string> ilceler = new List<string>();
        ViewBag.ilceler = new SelectList(db.Ilces.ToList(), "IlceId", "IlceAd");
        return View();//değiştirdim
    }
    [HttpPost]
    public ActionResult Ilcler(int ilid)
    {
        using (MVCAfetGirisContext db = new MVCAfetGirisContext())
        {
            // seçilen ulkenin id sine eşit olan şehirler seciliyor.
            List<Ilce> ilcem = db.Ilces.Where(x => x.Il.IlId == ilid).ToList();

            // şehirler listesini Json olarak gönderiyoruz.
            return Json(ilcem);
        }
    }

脚本;

<script type="text/javascript">
$(document).ready(function () {
    $('#iller').change(function () {
        var ilid = $(this).val();
        if (ilid != null && ilid != '') {
            $.ajax({
                type: "post",
                url: '@Url.Action("Ilcler", "AfetGirisController")',
                data: { ilid: ilid },
                success: function (ilcem) {
                    $('#ilceler').empty()
                    $.each(ilcem, function (YeniKayit, ilce) {
                        $('#ilceler').append($('<option/>', {
                            value: ilce.IlceId,
                            text: ilce.IlceAd
                        }));
                    });
                },
                error: function () {
                    alert("Hata");
                },
                beforeSend: function () {},
                complete: function () {}
            });
        }
    });
});

然后,

@Html.DropDownList("iller",ViewBag.iller as SelectList,"---İl---", new { style = "width:250px; height:28px;" })<br /><br />
@Html.DropDownList("ilcem", ViewBag.ilceler as SelectList, "---İlce---", new { style = "width:250px; height:28px;" })<br /><br />

0 个答案:

没有答案