2013-02-05 92 views
0

一直在爲此掙扎了一整天,我如何將actionlink id傳遞給jQuery ajax調用來啓用部分頁面更新。獲取點擊的ActionLink id並將其作爲函數參數傳遞

<li>@Html.ActionLink(@item.strCountry, "Index", "Weather", new { id = Regex.Replace(@item.strCountry, " ", "-") }, new { @class = "getCities" })</li> 

jQuery的

<script> 
$(function() { 
    $(".getCities").click(function() { 
     $.ajax({ 
      //url: this.href, 
      url: '@Url.Action("pvDisplayListOfWeatherCities", "Weather")', 
      type: 'GET', 
      data: { id: $('#id').val() }, 
      dataType: 'Json', 
      success: function (result) { 
       alert(result.test); 
      }, 
      error: function() { 
       alert("error"); 
      } 
     }); 
     return false; 
    }); 
}); 
</script> 

感謝

喬治

+2

作爲附加說明:'dataType'屬性區分大小寫。它應該是'「json」'而不是'「Json」'。 – LeGEC

回答

1

如果我理解正確的問題,那麼你改變:

data: { id: $('#id').val() },

data: { id: $(this).attr('id') },

編輯 - 所有你需要的是data: { id: $(this).text() },

+0

嗨boz,我已經試過,值仍然爲空,生成的html是

  • Afghanistan
  • 即使我可以只從'value'之間獲得'值'是我需要的所有 – CareerChange

    +0

    @CareerChange - 請參閱我的編輯:) – boz

    +0

    @ boz使用'text()'不會有同樣的效果,因爲設置爲文本的值可以在裏面有空格,並且由'Regex.Replace'代替鏈接的'id',所以我認爲控制器只需要帶空格的id更換。 –

    1

    添加參數(S)爲HTML屬性(S)

    <li>@Html.ActionLink(@item.strCountry, "Index", "Weather", 
        new { id = Regex.Replace(@item.strCountry, " ", "-") }, 
        new { @class = "getCities", data_param1 = Regex.Replace(@item.strCountry, " ", "-") })</li> 
    

    這將使:

    <li><a class="getCities" href="/Weather/Index/val" data-param1="val">country</a></li> 
    

    然後使用jQuery的.attr()方法:

    <script> 
    $(function() { 
        $(".getCities").click(function() { 
         $.ajax({ 
          //url: this.href, 
          url: '@Url.Action("pvDisplayListOfWeatherCities", "Weather")', 
          type: 'GET', 
          data: { id: $(this).attr("data-param1") }, // <-- param1 etc. 
          dataType: 'json', 
          success: function (result) { 
           alert(result.test); 
          }, 
          error: function() { 
           alert("error"); 
          } 
         }); 
         return false; 
        }); 
    }); 
    </script> 
    
    +0

    是否有可能在兩個選項都工作的情況下給予答案 – CareerChange

    +0

    @ CareerChange您可以投票給任何有用的答案,但只有一個可以被標記爲已批准。 –

    +0

    我已經標記每個人都在工作,謝謝大家的幫助 – CareerChange

    1

    你沒有設置id屬性此鏈接,你只是設置,作爲參數來建立鏈接本身的ID。如果你希望它是一樣在你的鏈接參數的id你應該簡單地添加id屬性此標記

    <li>@Html.ActionLink(@item.strCountry, "Index", "Weather", 
        new { id = Regex.Replace(@item.strCountry, " ", "-") }, 
        new { @class = "getCities", @id = Regex.Replace(@item.strCountry, " ", "-")})</li> 
    

    。然後更新這個

    data: { id: $('#id').val() }, 
    

    這個

    data: { id: $(this).attr('id') }, 
    

    得到這個HTML標籤的實際id屬性。

    相關問題