2012-03-09 36 views
5

我有一個註冊投票評論的方法。如果在投票時沒有錯誤,我通過PartialViewResult返回一小段html來更新頁面。如何爲PartialViewResult返回空字符串(或null)?

如果不成功,則不會發生任何事情。我需要在客戶端測試這種情況。

服務器端方法:

[HttpPost] 
public PartialViewResult RegisterVote(int commentID, VoteType voteType) { 
    if (User.Identity.IsAuthenticated) { 
     var userVote = repository.RegisterVote((Guid)Membership.GetUser().ProviderUserKey, commentID, voteType); 
     if (userVote != null) { 
      return PartialView("VoteButtons", userCommentVote.Comment); 
     } 
    } 

    return null; 
} 

客戶端腳本:

$(document).on("click", ".vote img", function() { 
    var image = $(this); 

    var commentID = GetCommentID(image); 
    var voteType = image.data("type"); 

    $.post("/TheSite/RegisterVote", { commentID: commentID, voteType: voteType }, function (html) { 
     image.parent().replaceWith(html); 
    }); 
}); 

如果投票記錄,在 「HTML」 變量containes標記預期。如果它不成功(即返回null),那麼「html」變量是一個帶有分析錯誤的「Document」對象。

有沒有辦法從PartialViewResult返回空字符串,然後只是測試長度?有沒有不同的/更好的方法來做到這一點?

回答

5

更改方法簽名來自:public PartialViewResult

要:public ActionResult

然後,而不是返回null,返回此:

return Json("");

這將允許你返回如果局部視圖如果不成功,它將只返回JSON,並使用空字符串作爲值。您當前的JS將按原樣工作。來自MSDN:

ActionResult類是操作結果的基類。

以下類型從派生的ActionResult:

  • ContentResult類型
  • EmptyResult
  • FileResult
  • HttpUnauthorizedResult
  • JavaScriptResult
  • JsonResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase

這是什麼讓你在你的方法返回不同派生類型。

+0

工作就像一個魅力。謝謝 – Jason 2012-03-09 04:10:01

0

倒不如返回一個JsonResult作爲,

[HttpPost] 
    public JsonResult RegisterVote(int commentID, VoteType voteType) 
    { 
     JsonResult result = new JsonResult(); 
     object content; 
     if (User.Identity.IsAuthenticated) 
     { 
      var userVote = repository.RegisterVote((Guid)Membership.GetUser().ProviderUserKey, commentID, voteType); 
      if (userVote != null) 
      { 
       content = new 
       { 
        IsSuccess = true, 
        VoteButtons = userCommentVote.Comment 
       }; 
      } 
      else 
      { 
       content = new { IsSuccess = false }; 
      } 
     } 
     result.Data = content; 
     return result; 
    } 

在Ajax調用,您可以驗證是否IsSuccesstruefalse

相關問題