2011-12-12 71 views
0
返回不同的JavaScript对象

我的控制器操作:从控制器

[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; 

     } 
    } 

根据不同的场景我想回到一个javascript并以某种方式通知了什么回来,基于结果的客户端做的成功的部分东西我的Ajax调用:

$.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") } 
     }); 
    }); 

我尝试过许多不同的变化,但我想,我需要这样的东西data.property1返回,并在客户端,以检查是否该属性存在,或soemthing这样的..请帮助

回答

1

您需要在对象中返回状态码。

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

然后在您的成功处理程序中检查data.status。

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

所以我可以做一些事情,如状态= 1或状态= 2,然后chchck状态它是什么数字它等于? –

+0

当然可以。 321 – BNL

+0

真棒,谢谢!〜 –