[英]Pass the variable values created in JavaScript to Server Side (Code Behind) in ASP.Net using C#
[英]Pass javascript var to asp.net code behind (c#)
我有問題,我想將javascript var傳遞到服務器端。
我想將var autocomplete
的值傳遞給名為Event_Address
字符串;
aspx.cs:
protected void ButtonAddEvent_Click(object sender, EventArgs e)
{
string Event_Address =hdnfldVariable.Value;
}
aspx:
var autocomplete;
<script type="text/javascript">
var somefunction = function() {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = autocomplete;
}
</script>
<asp:HiddenField ID="hdnfldVariable" runat="server" />
<asp:Button ID="ButtonAddEvent" runat="server" Text="הוסף אירוע חדש"
Font-Bold="True" Font-Names="Gisha" Font-Size="17pt" ForeColor="Blue"
onclick="ButtonAddEvent_Click"
style="z-index: 1; left: 497px; top: 774px; position: absolute" />
</asp:Content>
除了teo van kot的答案以外,如果HiddenField
的ClientID
是動態的,則應將其定義為動態的ClientID
如下所示:
var autocomplete = "[somevalue]";
<script type="text/javascript">
var somefunction = function() {
// set this if you have dynamic ClientID
var hdnfldVariable = document.getElementById("<%= hdnfldVariable.ClientID %>");
hdnfldVariable.value = autocomplete;
}
</script>
<asp:HiddenField ID="hdnfldVariable" runat="server" />
<asp:Button ID="ButtonAddEvent" runat="server" Text="הוסף אירוע חדש"
Font-Bold="True" Font-Names="Gisha" Font-Size="17pt" ForeColor="Blue"
onclick="ButtonAddEvent_Click"
OnClientClick="somefunction();"
style="z-index: 1; left: 497px; top: 774px; position: absolute" />
</asp:Content>
參考:
如果要在Button上調用您的js函數,請將其添加到OnClientClick
屬性。 像這樣:
var autocomplete;
<script type="text/javascript">
var somefunction = function() {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = autocomplete;
}
</script>
<asp:HiddenField ID="hdnfldVariable" runat="server" />
<asp:Button ID="ButtonAddEvent" runat="server" Text="הוסף אירוע חדש"
Font-Bold="True" Font-Names="Gisha" Font-Size="17pt" ForeColor="Blue"
onclick="ButtonAddEvent_Click"
OnClientClick="somefunction();"
style="z-index: 1; left: 497px; top: 774px; position: absolute" />
</asp:Content>
您可以將“自動完成”的值保存到隱藏字段,也可以使用ajax方法來調用ac#函數,以將值從前端傳遞到后端。
或者在您的情況下,使用attrbute屬性更改值。
請參閱此鏈接以獲取有關ajax的調用Ajax方法的調用
您可以在服務器端使用[Web Method]
。 您應該using System.Web.Services;
添加using System.Web.Services;
到使用網絡方法的CS代碼。 步驟如下:
PageMethods.YourWebMethod(yourParam);
傳遞變量PageMethods.YourWebMethod(yourParam);
在js中。 然后,您可以在服務器端Web方法中找到它。 這是您的前任:
function JsFunctionOnclick(){ PageMethods.MyPageMethod(myParameter); }
這是服務器端:
[WebMethod] public static void MyPageMethod(string param) { //do something }
確保您的網絡方法是靜態的祝您好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.