2012-02-19 112 views
3

我目前正試圖從我的視圖中調用一個方法來更改我的數據庫中的布爾值,唯一我不知道的,因爲我不熟悉MVC是每當我打電話給我的控制器方法,它給了我一個空白頁。我只是想調用這個方法,但留在實際的視圖中。在MVC中調用方法而不加載視圖

以下是我認爲的代碼部分。

<td><a href="@Url.Action("PutInBin", "Capture", new { captureId = @Model.Files.Captures.ElementAt(i).Capture_Id })", onclick="DeleteCapture(@(i + 1))">Delete</a></td> 

這裏是我的控制器的方法

public void PutInBin(int captureId) 
    { 
     QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin(); 
     queryCaptureToBin.Capture_Id = captureId; 
     client.PlaceCaptureInBin(queryCaptureToBin, userParams); 
    } 

回答

10

你可以使用AJAX:

<td> 
    @Ajax.ActionLink(
     "Delete", 
     "PutInBin", 
     "Capture", 
     new { 
      captureId = Model.Files.Captures.ElementAt(i).Capture_Id 
     }, 
     new AjaxOptions { 
      HttpMethod = "POST", 
     } 
    )  
</td> 

,不要忘了包括jquery.unobtrusive-ajax.js腳本到你的頁面:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script> 

和你的控制器動作:

[HttpPost] 
public ActionResult PutInBin(int captureId) 
{ 
    QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin(); 
    queryCaptureToBin.Capture_Id = captureId; 
    client.PlaceCaptureInBin(queryCaptureToBin, userParams); 
    return new EmptyResult(); 
} 

,如果你想獲得通知時,刪除完成:

<td> 
    @Ajax.ActionLink(
     "Delete", 
     "PutInBin", 
     "Capture", 
     new { 
      captureId = Model.Files.Captures.ElementAt(i).Capture_Id 
     }, 
     new AjaxOptions { 
      HttpMethod = "POST", 
      OnSuccess = "onDeleteSuccess" 
     } 
    )  
</td> 

,然後你就會有你的onDeleteSuccess javascript函數:

var onDeleteSuccess = function(result) { 
    // normally the result variable will contain the response 
    // from the server but in this case since we returned an EmptyResult 
    // don't expect to find anything useful in it. 

    alert('The capture was successfully deleted'); 
}; 
+0

它的工作原理就像一個魅力,非常感謝Darim! – Oflocet 2012-02-19 09:39:06

+0

作品!但表格不會自動刷新。我怎樣才能刷新它? – user2254436 2014-05-20 11:03:49

0

要刷新頁面。請使用下面的java腳本功能。它與上面相同,但刪除了「alert」並使用了window.location.reload(true)。在html或cshtml視圖中使用。致敬原來的主人


<script> 

    var onDeleteSuccess = function(result) { 

     // normally the result variable will contain the response 
     // from the server but in this case since we returned an EmptyResult 
     // don't expect to find anything useful in it. 

     window.location.reload(true); 

     // alert('The capture was successfully deleted'); 

    }; 

</script> 
相關問題