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?
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:
This is what allows you to return different derived types in your method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With