【问题标题】:Ajax.ActionLink, get data or error message from controller?Ajax.ActionLink,从控制器获取数据或错误消息?
【发布时间】:2012-04-22 22:36:37
【问题描述】:

这是我要更新的地方:

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

这是我的操作链接:

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

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

谢谢。

【问题讨论】:

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


    【解决方案1】:
    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);   
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-18
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2020-01-19
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多