Alan Budzinski
Alan Budzinski

Reputation: 809

returning different javascript object from controller

my controller action:

 [HttpPost]
    public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
    {   
        if (CheckIfAddPointToSelf(User.Identity.Name, id))
        {
            var song = repository.GetSong(id);
            foreach (var item in song.Points)
            {
                if (User.Identity.Name == item.UsernameGavePoint)
                {
                   var data1 = 1;


                    return Json(new {data1}, JsonRequestBehavior.AllowGet);
                }

            }
            var originalSong = repository.GetSong(id);
            var newSong = new Song();
            newSong.UserName = User.Identity.Name;
            newSong.Title = originalSong.Title;
            newSong.YoutubeLink = originalSong.YoutubeLink;
            newSong.GenreId = 38;
            newSong.Date = DateTime.Now;

            repository.AddSong(newSong);

            var point = new Point();
            point.UsernameGotPoint = originalSong.UserName;
            point.UsernameGavePoint = User.Identity.Name;
            point.Date = DateTime.Now;
            point.Score = 1;
            point.OtherSongId = id;
            repository.AddPoint(point);
            repository.Save();

           int data = 2;
            //process here
            return Json(new { data }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return null;

        }
    }

based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:

  $.ajax({
            beforeSend: function () { ShowAjaxLoader(); },
            url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
            type: "POST",
            data: { id: songId },
            success: function (data,one) {

                if (data && !one) {
                    HideAjaxLoader(), ShowMsg("Song Added Successfully");
                }
                else if(!data) {
                    HideAjaxLoader(), ShowMsg("you cannot add your own songs");
                }
                else if (data && one) {
                    HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
                }
            },
            error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
        });
    });

I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help

Upvotes: 0

Views: 449

Answers (1)

BNL
BNL

Reputation: 7133

You need to return your status code within the object.

return Json( new { data1 = "Some Other Data", status = 1} );

Then in your success handler check data.status.

if (data.status === 1) {
     alert(data.data1);
} 

Upvotes: 1

Related Questions