Ajax.ActionLink, get data or error message from controller?

蹲街弑〆低调 提交于 2019-12-08 04:54:30

问题


Here is a spot that I want to update:

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

Here is my 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"
})

And here is one of my controllers:

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

And my question: I want to send error message or an integer to my view page to show it. How can I do it? From advices that you have recommended, I can change all codes.

Thanks.


回答1:


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

Whatever text you return in the content result will be inserted into the div.

Another possibility is to use JSON:

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

and then:

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

and finally inside the onSuccess callback:

function onSuccess(result) {
    if (result.error) {
        alert(result.error);
    } else {
        $('#vote_count').html(result.votes);   
    }
}


来源:https://stackoverflow.com/questions/10272733/ajax-actionlink-get-data-or-error-message-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!