2012-01-21 40 views
46

ASP.NET MVC操作方法我有這樣的代碼示例:從JavaScript調用

<div class="cart"> 
     <a onclick="addToCart('@Model.productId');" class="button"><span>Add to Cart</span></a> 
</div> 
<div class="wishlist"> 
     <a onclick="addToWishList('@Model.productId');">Add to Wish List</a> 
</div> 
<div class="compare"> 
     <a onclick="addToCompare('@Model.productId');">Add to Compare</a> 
</div>  

我如何編寫JavaScript代碼來調用控制器的操作方法?

回答

50

使用jQuery的ajax:

function AddToCart(id) 
{ 
    $.ajax({ 
     url: 'urlToController', 
     data: { id: id } 
    }).done(function() { 
     alert('Added'); 
    }); 
} 

http://api.jquery.com/jQuery.ajax/

+2

感謝Kman,它的工作,你可以簡單地添加這個... –

+5

沒有與例如語法錯誤上面,因爲應該有一個逗號後的數據:{id:id},但不幸的是,它被認爲是太微不足道的修改我修復。 – Sterno

+0

@Sterno我排隊等候同行評議。感謝您離開您的帖子;它加快了我的故障排除過程。 – DigitalNomad

9

如果你想從你的JavaScript調用一個動作,一個方法就是嵌入到你的JavaScript代碼,您的視圖中(.cshtml文件爲例),然後使用Razor創建該動作的URL:

$(function(){ 
    $('#sampleDiv').click(function(){ 
     /* 
     While this code is JavaScript, but because it's embedded inside 
     a cshtml file, we can use Razor, and create the URL of the action 

     Don't forget to add '' around the url because it has to become a  
     valid string in the final webpage 
     */ 

     var url = '@Url.Action("ActionName", "Controller")'; 
    }); 
}); 
+0

感謝saeed,爲您提供幫助... –

+0

ANY在.js文件中使用這種代碼的建議? –

10

您正在調用addToCart方法並傳遞產品ID。現在您可以使用jQuery ajax將該數據傳遞給您的服務器端操作方法。

jQuery post是jQuery ajax的簡短版本。

function addToCart(id) 
{ 
    $.post('@Url.Action("Add","Cart")',{id:id } function(data) { 
    //do whatever with the result. 
    }); 
} 

如果你想更喜歡成功的回調和錯誤處理選項,使用jQuery阿賈克斯,

function addToCart(id) 
{ 
    $.ajax({ 
    url: '@Url.Action("Add","Cart")', 
    data: { id: id }, 
    success: function(data){ 
    //call is successfully completed and we got result in data 
    }, 
    error:function (xhr, ajaxOptions, thrownError){ 
        //some errror, some show err msg to user and log the error 
        alert(xhr.responseText); 

       }  
    }); 
} 

當進行AJAX調用,我強烈建議使用HTML輔助方法,如Url.Action生成路徑到你的行動方式。

如果您的代碼位於剃鬚刀視圖中,這將起作用,因爲Url.Action將由服務器端的剃鬚刀執行,並且c#表達式將被替換爲正確的相對路徑。但是,如果您在外部js文件中使用jQuery代碼,則可以考慮在此answer中提到的方法。

10

如果你不需要太多的定製和尋求簡單性,你可以用內置的方式 - AjaxExtensions.ActionLink method

<div class="cart"> 
     @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" }); 
</div> 

這MSDN鏈接必讀此方法的所有可能的過載和AjaxOptions class參數。其實,你可以使用確認,更改http方法,設置的onSuccess和onFailure處的客戶端腳本等

0

你可以設置你的element

value="@model.productId"

onclick= addToWishList(this.value);

11

您可以簡單地通過使用行動方法的Javascript,如下圖所示:

var id = model.Id; //if you want to pass an Id parameter 
window.location.href = '@Url.Action("Action", "Controller")/' + id; 

希望這有助於...

1
Javascript Function 

function AddToCart(id) { 
$.ajax({ 
    url: '@Url.Action("AddToCart", "ControllerName")', 
    type: 'GET', 
    dataType: 'json', 
    cache: false, 
    data: { 'id': id }, 
    success: function (results) { 
     alert(results) 
    }, 
    error: function() { 
    alert('Error occured'); 
    } 
    }); 
    } 

Controller Method to call 

[HttpGet] 
    public JsonResult AddToCart(string id) 
    { 
    string newId = id; 
    return Json(newId, JsonRequestBehavior.AllowGet); 
    } 
3

當您使用相同的控制器來重定向

var url = "YourActionName?parameterName=" + parameterValue; 
window.location.href = url; 
+0

你也可以使用不同的控制器,'var url =「YourController/YourActionName?parameterName =」+ parameterValue; window.location.href = url;' –