2012-04-22 81 views
1

這裏是我想更新的地點: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 
    } 
} 

我的問題:我想發送錯誤消息或整數到我的視圖頁來顯示它。我該怎麼做? 從您建議的建議中,我可以更改所有代碼。

謝謝。

回答

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