Mvc Jquery Ajax功能不起作用

时间:2017-04-06 05:14:18

标签: javascript jquery ajax asp.net-mvc

无法使用ajax功能,我可以工作吗?我想用mvc ajax显示通知。但是我使用ActionResult复出返回RedirectToAction(" myAction"," myControl"),我可以制作。 感谢帮助 .. 我的示例代码:

    $(document).ready(function () {
    $.ajax({
        url: '/Kategori/KategoriEkle',
        type: 'POST',
        data: "{}",
        datatype: 'html',
        success: function () {
            var unique_id = $.gritter.add({

                title: 'Welcome to Home!',
                text: 'Message',
                //image: '/assets/img/ui-sam.jpg',
                sticky: true,
                time: '',
                class_name: 'my-sticky-class'
            });

            return false;
        }
    });
});

Kategori.cs

    [HttpPost]
    public ActionResult KategoriEkle(Kategori kategori)
    {
        KutuphaneContext db = new KutuphaneContext();
        var con = db.Kategori.Where(x => x.KategoriAdi == kategori.KategoriAdi).Count();

        if (con <= 0 && kategori.KategoriAdi != null)
        {                
            _kategoriRepository.Insert(kategori);
            _kategoriRepository.Save();
        }

        return RedirectToAction("Kategoriler", "Kategori");
    }

}

1 个答案:

答案 0 :(得分:0)

这可能会帮到你。重定向Ajax调用方法而不是控制器

  1. 在控制器中返回Json

    [HttpPost]
    public ActionResult KategoriEkle(Kategori kategori)
    {
        KutuphaneContext db = new KutuphaneContext();
        var con = db.Kategori.Where(x => x.KategoriAdi ==     kategori.KategoriAdi).Count();
    
        if (con <= 0 && kategori.KategoriAdi != null)
        {                
            _kategoriRepository.Insert(kategori);
            _kategoriRepository.Save();
        }
        url = Url.Action("Kategoriler", "Kategori");
        redirect = true;
    
        return Json(new
        {
            redirectUrl = url,
            isRedirect = redirect
        }, JsonRequestBehavior.AllowGet);
    }
    
  2. 在Ajax Call中

           $.ajax({
           url: '/Kategori/KategoriEkle',
           type: 'POST',
           data: "{}",
           datatype: 'json',
           contentType: "application/json; charset=utf-8",
           success: function () {
           var unique_id = $.gritter.add({
    
            title: 'Welcome to Home!',
            text: 'Message',
            //image: '/assets/img/ui-sam.jpg',
            sticky: true,
            time: '',
            class_name: 'my-sticky-class'
    
            if (response.isRedirect) {
                window.location.href = response.redirectUrl;
                return false;
            }
            else {
                alert('Error occurred.');
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }