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

Ali*_*hşi 1 asp.net-mvc asp.net-ajax actionlink

这是我要更新的地方:

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

这是我的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"
})
Run Code Online (Sandbox Code Playgroud)

这是我的一个控制器:

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

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

谢谢.

Dar*_*rov 16

public ActionResult Upvote(Guid QuestionID)
{
    if (...)
    {
        return Content("some error message");
    }
    else 
    {
        return Content("5 votes");
    }
}
Run Code Online (Sandbox Code Playgroud)

您在内容结果中返回的任何文本都将插入到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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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

最后在onSuccess回调中:

function onSuccess(result) {
    if (result.error) {
        alert(result.error);
    } else {
        $('#vote_count').html(result.votes);   
    }
}
Run Code Online (Sandbox Code Playgroud)