2016-07-05 59 views
1

我使用ajaxform和MVC。MVC控制器在更新Div內容前返回內容

如何更新像 return RedirectToAction("action","controller")

之前調用諸如回報Content("Successfully update")消息JavaScript或無javascript格的內容?

像 控制器:

if(Success) 
    { 
     return Content("Successfully updated"); 
    } 
    else 
    { 
     return Content("Error"); 
    } 

剃刀:

<div id="result"> 

<form action="/controller/action" data-ajax-update="#result" 
    data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" method="post "> 

<!-- Inputs was here --> 
    </form> 

    <div id="Content "> 

<!-- DataList (partial content) was here -->  
    </div> 
+1

請注意,模型 - 視圖 - 控制器標籤有關該模式的問題。 ASP.NET-MVC實現有一個特定的標籤。 –

回答

1

您可以使用AjaxOptions:

@using (Ajax.BeginForm("action", "controller", new AjaxOptions 
         { UpdateTargetId = "Content", 
          OnFailure = "OnFailure", 
          OnSuccess = "OnSuccess"})) 
{ 
... 
} 
01在的onSuccess JS功能

if(Success) 
    { 
     return Content("Successfully updated"); 
    } 
    else 
    { 
     return Json(new { success = false, message = "Error!"}); 
    } 

然後:

然後

<script type="text/javascript"> 

    function OnSuccess(data) { 
     $("#Content").html("Successfully updated"); 
    } 
    function OnFailure(request, error) { 
     alert("Error!"); 
    } 

</script> 
+0

沒有。但如果不成功,內容將更新錯誤消息。 – caras

+0

@caras請給我更多的細節,因爲現在有點不清楚你想要什麼 – Marusyk

+1

我認爲@MegaTron的答案已經確定。使用OnSuccess和OnFailure函數來操作數據。 – denchu

0

的控制器應檢查然後

function OnSuccess(data) { 
     if (data.success === false){ 
      alert(data.message); 
      $("#Content").html(data.message); 
     } 
     else 
      $("#Content").html(data); 

}