Search code examples
ajaxasp.net-mvcmodel-view-controllerrazor

Ajax call asp.net mvc 5 controller, parameter return null


I try to call my controller using ajax. But my parameter return null when I reach the controller Here is my code for view

function ajaxfunction(id) {
        var serviceURL = '/Users/AddWishList';
        alert("inside ajax");
        alert(id);
        $.ajax({
            type: "POST",
            url: serviceURL,
            data: roomID = id ,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {
            alert(data);
        }

        function errorFunc() {
            alert('error');
        }
    };

The alert(id) is showing the data properly, but when I reach the controller it returns null. enter image description here

[HttpPost]
        public JsonResult AddWishList(string roomID)
        {
            wishList wish = new wishList();
            wish.roomID = roomID;
            var user = _context.UsersDB.Where(u => u.userName == HttpContext.User.Identity.Name).FirstOrDefault();
            wish.userID = user.userID.ToString();
            _context.wishListDB.Add(wish);
            _context.SaveChanges();
            return Json("Room added to your wish list",JsonRequestBehavior.AllowGet);
        }

and the return message also cannot be display, which is "data" inside the ajax. Can someone help?


Solution

  • You have to pass object to controller. Replace:

    data: roomID = id ,
    

    with

    data: JSON.stringify({'roomID' : id}) ,
    

    this should work, as expected.