2

这是我要更新的地方:

<div style="text-align: center;" id="vote_count">@Html.DisplayFor(q => q.VoteCount)</div>

这是我的actionLink:

@Ajax.ActionLink("Upvote", "Upvote", "Author", new { QuestionID = Model.QuestionID, @class = "upvote" },
new AjaxOptions
{
     InsertionMode = InsertionMode.Replace,
     UpdateTargetId = "vote_count",
     OnBegin = "onBegin",
     OnComplete = "onComplete",
     OnSuccess = "onSuccess",
     OnFailure = "onFailure"
})

这是我的控制器之一:

public int Upvote(Guid QuestionID)
{
    if ()
    {
        //I want to send error message
    }
    else 
    {
        //I want to send an integer
    }
}

我的问题是:我想向我的视图页面发送错误消息或整数来显示它。我该怎么做?根据您推荐的建议,我可以更改所有代码。

谢谢。

4

1 回答 1

18
public ActionResult Upvote(Guid QuestionID)
{
    if (...)
    {
        return Content("some error message");
    }
    else 
    {
        return Content("5 votes");
    }
}

您在内容结果中返回的任何文本都将插入到 div 中。

另一种可能性是使用 JSON:

public ActionResult Upvote(Guid QuestionID)
{
    if (...)
    {
        return Json(new { error = "some error message" }, JsonRequestBehavior.AllowGet);
    }
    else 
    {
        return Json(new { votes = 5 }, JsonRequestBehavior.AllowGet);
    }
}

接着:

@Ajax.ActionLink("Upvote", "Upvote", "Author", new { QuestionID = Model.QuestionID, @class = "upvote" },
new AjaxOptions
{
     OnSuccess = "onSuccess"
})

最后在 onSuccess 回调中:

function onSuccess(result) {
    if (result.error) {
        alert(result.error);
    } else {
        $('#vote_count').html(result.votes);   
    }
}
于 2012-04-23T06:13:15.873 回答