Why does the Ajax call not return the data from the action to the success callback function?

时间:2019-03-19 14:46:47

标签: javascript c# ajax asp.net-mvc

I'm trying to get the partial view html to append to the content of Modal-popup box.The following script is supposed to run "Details" action when button is clicked and return the html output to the succes callback. So ActionMethod runs but I couldn't get the corresponding view back as parameter - alert doesn't show up! Could you spot anything wrong in that script? What is the reason I couldn't get the view back?

<!--language: lang-js-->
<script> 
        $(".detail-link").click(function () {
            var Did = $(this).data("id");
            $.ajax({
                type: 'POST',
                url: "/Home/Details/",
                data: { id: Did },
                dataType: 'html',
                succes: function myfunction(data){
                    alert(data);
                 }
            });
        });
    </script>

This is action method named "Details"

<!--language: lang-cs-->
 [HttpPost]
        public ActionResult Details(int? id)
        {

            HomeModel model = new HomeModel();
            var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
            if (book == null)
            {
                HttpNotFound();
            }

            book.DisplayNumber++;
            db.SaveChanges();
            model.bookDetails = book;
            return PartialView(model);
        }

I might also post the view that I want to get back if it's required

1 个答案:

答案 0 :(得分:1)

Change ActionResult to JsonResult and return Json object.

[HttpPost]
        public JsonResult Details(int? id)
        {

            HomeModel model = new HomeModel();
            var book = db.Books.Where(b => b.Id == id).Include(b => b.Author).SingleOrDefault();
            if (book == null)
            {
                HttpNotFound();
            }

            book.DisplayNumber++;
            db.SaveChanges();
            model.bookDetails = book;
            return Json(model);
        }