How can I return an empty string (or null) for a PartialViewResult?

I have a method that registers a vote for a comment. If there are no errors during the voting, I return a small html fragment via PartialViewResult to refresh the page.

If this fails, nothing should happen. I need to check this condition on the client side.

Server side method:

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

Client side script:

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

If the vote was recorded, the "html" variable contains the markup as expected. If this fails (that is, Null was returned), then instead of the "html" variable, there is instead a "Document" object with a parsing error.

Is there a way to return an empty string from PartialViewResult and then just check the length? Is there any other / better way to do this?

+5
2

: public PartialViewResult

To: public ActionResult

null :

return Json("");

, , , JSON ​​ . JS , . MSDN:

ActionResult .

ActionResult:

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

.

+5

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 , IsSuccess true false.

0
source

All Articles