Javascript 如何为PartialViewResult返回空字符串(或null)?
我有一种方法,可以为评论注册投票。如果投票时没有错误,我会通过PartialViewResult返回一小段html来更新页面 如果不成功,什么也不应该发生。我需要在客户端测试这种情况 服务器端方法:Javascript 如何为PartialViewResult返回空字符串(或null)?,javascript,jquery,asp.net-mvc-3,Javascript,Jquery,Asp.net Mvc 3,我有一种方法,可以为评论注册投票。如果投票时没有错误,我会通过PartialViewResult返回一小段html来更新页面 如果不成功,什么也不应该发生。我需要在客户端测试这种情况 服务器端方法: [HttpPost] public PartialViewResult RegisterVote(int commentID, VoteType voteType) { if (User.Identity.IsAuthenticated) { var userVote = r
[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);
});
});
客户端脚本:
[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返回一个空字符串,然后只测试长度?是否有其他/更好的方法来执行此操作?将方法签名更改为:
public PartialViewResult
致:public ActionResult
然后返回以下内容,而不是返回null:
返回Json(“”)代码>
如果成功,这将允许您返回部分视图,如果不成功,它将只返回JSON,值为空字符串。您当前的JS将按原样工作。从MSDN:
ActionResult类是操作结果的基类
以下类型派生自ActionResult:
- 内容结果
- 空结果
- 文件结果
- HttpUnauthorizedResult
- JavaScriptResult
- JsonResult
- 重定向结果
- 重定向路由结果
- ViewResultBase
这就是允许您在方法中返回不同派生类型的原因。最好将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调用中,您可以验证issucess
是true
还是false