Ajax.ActionLink, get data or error message from controller?
actionlink, asp.net-ajax, asp.net-mvc
Solution
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);
}
}
Problem
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.