2016-11-10 88 views
-1

請參見下面的代碼:填充全局變量

@{ 
    var propertyList = new List<Tuple<string, string>>(); 
} 

<input type="text" data-id="@item.Item1" class="form-control prop"/> 

<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId, propList = propertyList})"> Run Report</a> 

<script> 
    $("#run-report").click(function() { 
     $(".prop").each(function() { 
      var currentProp = $(this).attr("data-id"); 
      var currentPropVal = (this).value; 

      @{ 
       propertyList.Add(new Tuple<string, string>("", "")); 
      } 

     }); 
    }); 

</script> 

正如你可以在上面看到,我有一個全局變量稱爲propertyList含元組列表,<string, string>

我在此聲明,因爲我需要使用Url.Action從我的控制器操作直接下載報告。

當我從我的文本框中獲取值時,我碰到了一堵牆。我需要將我的jQuery的值添加到我的全局元組列表中。

它看起來不像我可以這樣做。

任何意見將不勝感激!

感謝

+1

你在混合客戶端和服務器端代碼。服務器端代碼'@ {}'在到達瀏覽器之前運行,並且在此之後不能更改。 –

+1

考慮到Razor首先在服務器中編譯,然後jQuery在瀏覽器中執行... –

回答

1

記住@{}代碼運行服務器端,所以在它到達瀏覽器。一旦它在瀏覽器中「呈現」,就好像它是純文本並且不能改變。

您可以通過在腳本中建立他們通​​過你的參數,例如:

從Url.Action參數刪除帕拉姆

<input type="text" data-id="@item.Item1" class="form-control prop"/> 
<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId})"> Run Report</a> 

通過腳本

$("#run-report").click(function() { 

    var url = $(this).attr("href"); 

    $(".prop").each(function() { 
     var currentProp = $(this).data("id"); 
     var currentPropVal = (this).value; 

     url += "?" + currentProp + "=" + currentPropVal; 
    }); 

    location.href = url; 
}); 

根據加入他們根據您的操作預期的格式,您可能需要更改網址的構建方式,但這顯示了原則。