简体   繁体   中英

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?

You have to pass object to controller. Replace:

data: roomID = id ,

with

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

this should work, as expected.

It is much more simple to use GET in this case but if you still want to use POST you will have to use a ViewModel

public class ViewModel
{
 public string  RoomID {get;set;}
}

and change the action header:

[HttpPost]
 public JsonResult AddWishList(ViewModel viewModel)
 {
 var roomID=viewModel.RoomId;
....
}

use this ajax code:

function ajaxfunction(id) {
        var serviceURL = '/Users/AddWishList';
      
        $.ajax({
            type: "POST",
            url: serviceURL,
            data: {roomID = id} ,
            success: successFunc,
            error: errorFunc
        });

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

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

if you deside to use GET:

[Route("{roomId}")]
 public JsonResult AddWishList(string roomID)

and ajax

 var serviceURL = '/Users/AddWishList/'+id;

 $.ajax({
 type: "GET",
 url: serviceURL,
  success: successFunc,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM