如何为PartialViewResult返回空字符串(或null)?

时间:2012-03-09 01:54:04

标签: javascript jquery asp.net-mvc-3

我有一种注册投票的方法。如果在投票时没有错误,我会通过PartialViewResult返回一小段html来更新页面。

如果不成功,什么都不应该发生。我需要在客户端测试这种情况。

服务器端方法:

[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”变量会按预期包含标记。如果它没有成功(即返回null),那么“html”变量就是一个带有解析错误的“Document”对象。

有没有办法从PartialViewResult返回一个空字符串然后只测试长度?是否有不同/更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:5)

public PartialViewResult

更改您的方法签名

收件人:public ActionResult

然后返回此代码而不是返回null:

return Json("");

如果成功,这将允许您返回部分视图,否则,它将返回带有空字符串的JSON作为值。您当前的JS将按原样运行。来自MSDN:

ActionResult类是操作结果的基类。

以下类型派生自ActionResult:

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

这使您可以在方法中返回不同的派生类型。

答案 1 :(得分: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调用中,您可以验证IsSuccesstrue还是false