Ajax.ActionLink,从控制器获取数据或错误消息?

时间:2012-04-22 22:36:37

标签: asp.net-mvc asp.net-ajax actionlink

这是我要更新的地方:

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

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

感谢。

1 个答案:

答案 0 :(得分:16)

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