Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a method which registers a vote for a comment. If there are no errors while casting the vote, I return a small snippet of html via a PartialViewResult to update the page.

If it does not succeed, nothing should happen. I need to test for this condition on the client side.

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

The 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 containes markup as expected. If it does not succeed (i.e. null was returned) then the "html" variable is instead a "Document" object with a parse error.

Is there a way to return an empty string from the PartialViewResult and then just test for length? Is there a different/better way to do this?

like image 315
Jason Avatar asked Mar 09 '12 01:03

Jason


1 Answers

Change your method signature from: public PartialViewResult

To: public ActionResult

Then instead of returning null, return this:

return Json("");

This will allow you to return a partial view if successful, if not, it will just return JSON with an empty string as the value. Your current JS will work as is. From MSDN:

The ActionResult class is the base class for action results.

The following types derive from ActionResult:

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

This is what allows you to return different derived types in your method.

like image 145
Paul Avatar answered Oct 15 '22 08:10

Paul