2012-03-09 62 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