2014-04-11 20 views
0

我有一個jQuery腳本,每當一個下拉downlist值的變化,它應該採取的價值,並將其傳遞到該得到的值,並基於該值,然後在價格的方法結束設定標籤到新值。如何在使用jQuery腳本時訪問方法?

這裏是我的jQuery腳本:

@section PageScripts{ 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#paperTypeJList').change(function() { 
      // trying to figure out how to pass the value to the following method 
     }); 
    }); 
</script> 
} 

這裏是我的方法,我試圖給jQuery腳本里面叫:

public decimal getNewPrice(string dropdownValue) 
    { 
     // do something with value and return a decimal 
     return 0; 
    } 
+0

你需要使用[jQuery的阿賈克斯(https://api.jquery.com/jQuery.ajax/) –

+0

沒有帖子或表單提交,「HTML」客戶端無法訪問服務器邏輯。如上所述,您需要利用Ajax等技術。 –

+0

真正的問題是你甚至需要這樣做?操作是否需要數據訪問?如果沒有,你可能只需在javascript內部執行該操作即可。沒有必要矯枉過正。 – kmacdonald

回答

0

試試這個使用jQuery阿賈克斯 HTML:

<label id="priceLabel"></label> 

的Javascript

$(document).ready(function() { 
    $('#paperTypeJList').change(function() { 
     $.ajax({ 
      type: "GET", 
      url: "/Home/getNewPrice?dropdownValue=" + this.value, 
      async: true, 
      success: function (result) { 
       document.getElementById('priceLabel').innerHTML = result; 
      } 
     }); 
    }); 
}); 

控制器

public decimal getNewPrice(string dropdownValue) 
    { 
     // do something with value and return a decimal 
     return 5.72M; 
    } 
+0

這段代碼不適合我。我瞭解代碼以及它在做什麼,我在想,url部分正在拋棄。我的下拉列表是在視圖索引頁面中創建的,我試圖調用的方法位於homecontroller.cs類中,這樣會改變什麼? –

+0

@FranklinJosephMoormann每當你的下拉改變代碼將調用你的homecontroller中的方法,你在哪裏做計算並返回結果,因此你可以在你的ajax.success中設置標籤 – Nilesh

+0

我複製了代碼字,並編輯我的方法,所以它返回5.72用於測試目的,它不會將標籤值更改爲任何東西,無論我嘗試什麼。我很沮喪:( –

1

你必須發送AJAX使用jquery調用服務器。

事情是這樣的:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#paperTypeJList').change(function() { 
      // trying to figure out how to pass the value to the following method 
     var value = $(this).val(); 

$.ajax({ 
    url: '@Url.Action("Action","Controller")', 
    data: {dropdownValue:value}, 
    cache: false, 
    success: function(response){ 
    alert(response); 
    } 
}); 

    }); 

    }); 
</script> 
+0

我想這個代碼,但我得到的語法錯誤每次。你確定代碼是正確的嗎?數據值之後不應該有逗號嗎?還有應該在@ Url.Action之前有一個撇號嗎? –

+0

是的,是的數據屬性後放,讓我更新 –

+0

現在不應該放棄語法錯誤 –

0
$(document).ready(function() { 
     $('#paperTypeJList').change(function() { 
      getNewPrice($(this).val()); 
     }); 
    }); 
0

我當前的代碼如下:

@section PageScripts{ 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#paperTypeJList').change(function() { 
      $.ajax({ 
      type: "GET", 
      url: "/Home/getNewPrice?dropdownValue=" + this.value, 
      async: true, 
      success: function (result) { 
        document.getElementById('priceLabel').innerHTML = result; 
      } 
     }); 
     }); 
     }); 
</script> 

}

public decimal getNewPrice(string dropdownValue) 
    { 
     // do something with value and return a decimal 
     return 5.72M; 
    } 
相關問題