在后面的代码中访问 .cs 文件中的 javascript 变量值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11077366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:02:20  来源:igfitidea点击:

Access javascript variable's value in .cs file that is in in code behind?

javascriptasp.nethtmljsonc#

提问by Zoya

I want to access java script's return value , which in is in a variable and a label, i want to use it in .cs file, how do i do that? I have fetch the out put of javascript in a variable and also a label control of asp.net... I get the values both the ways, but in need it .cs file to save it in my data bsae, help me please.. Thank u

我想访问 java 脚本的返回值,它在一个变量和一个标签中,我想在 .cs 文件中使用它,我该怎么做?我已经在一个变量和 asp.net 的标签控件中获取了 javascript 的输出......我得到了两种方式的值,但需要它的 .cs 文件将它保存在我的数据 bsae 中,请帮助我。 。 感谢你

<script language=Javascript>
    function setup_ip(json) {
        var htmlx = " Your IP Address: <b>" + json.IP;
        htmlx += "</b> | Country: " + json.countryName;
        if (json.cityName != "Unknown" || json.regionName != "Unknown") {
            htmlx += " | City: " + json.cityName + " / " + json.regionName;
            var s = " | City: " + json.cityName + " / " + json.regionName;
        } else {
            htmlx += " | Your Time: " + json.localTimeZone;
        }

        $("#myipx").html(htmlx);
     //   $('#<%= lbl1.ClientID %>').text(htmlx);
        $('#<%= lbl1.ClientID %>').text(s);

       // var txtCountry = document.getElementById('<%=lbl1.ClientID %>');        

    }

    $(document).ready(function() {


        EasyjQuery_Get_IP("setup_ip", "full");

    });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div class="inner">
<p class="welcome-message">
<a href="http://www.easyjquery.com/detect-get-clients-ip-address-country-using-javascript-php/"id="topid" title="Javascript, PHP jQuery API Detect Clients IP Address and Country - Geo Location"   >
<asp:Label ID="myipx" runat="server"  ClientIDMode="Static"></a></asp:Label>Detecting Clients IP Address - Country - City</span>
<br />
<asp:Label ID="lbl1" runat="server"  ClientIDMode="Static"></asp:Label>
                </p>
                 <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>


            <!-- END #footer-texture -->
            </div>

    </div>
    </form>
</body>

回答by T.J. Crowder

To send client-side information (the JavaScript result/variable) to the server, you must...send the information to the server. :-) You can do that in a variety of ways, the two best for updating a database would be:

要将客户端信息(JavaScript 结果/变量)发送到服务器,您必须...将信息发送到服务器。:-) 您可以通过多种方式做到这一点,更新数据库的两种最佳方式是:

  • Ajax- A means of sending data from the client to the server without page refresh
  • Form submission - A standard form submission
  • Ajax- 一种无需刷新页面即可将数据从客户端发送到服务器的方法
  • 表单提交 - 标准表单提交

回答by Raab

Create a server side hidden field, Place javascript value in it. and read value form hidden field on server side.

创建一个服务器端隐藏字段,在其中放置 javascript 值。并从服务器端的隐藏字段中读取值。

Html

html

<input type="hidden" id="myhidden" runat="server">

Access in javascript

在javascript中访问

 document.getElementById("myhidden").value="jsvalue";

Access in code behind

在后面的代码中访问

myhidden.Value

OR

或者

you can use ajax to send data to the server.

您可以使用ajax向服务器发送数据。

回答by Sunny

To use this values you have following options :

要使用此值,您有以下选项:

1.)As label is your server side control you can easily access label text value in .cs file so main issue with javascript variable here you can assign this value to asp:hidden field so you can also access this in .cs file like :

1.) 由于标签是您的服务器端控件,您可以轻松访问 .cs 文件中的标签文本值,因此这里的 javascript 变量的主要问题您可以将此值分配给 asp:hidden 字段,以便您也可以在 .cs 文件中访问它,例如:

<script language=Javascript>
function setup_ip(json) {

$("#hdn").val('your javascript variable');
}
</script>
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Release">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpnlHidden" runat="server">
    <ContentTemplate>
        <input runat="server" type="hidden" id="hdn" value="0" />
    </ContentTemplate>
</asp:UpdatePanel>

cs file :

.cs 文件:

  string str = hdn.value//Where ever you want to store value

2.)Another option you can use pagemethod here and pass both values as parameter to .cs file.

2.) 另一个选项,您可以在此处使用 pagemethod 并将两个值作为参数传递给 .cs 文件。

javascript :

javascript :

  PageMethods.getValue(parameter1,parameter2, OnSucceeded, OnFailed);
function OnSucceededID(result, methodName)
{
   //get result back if you want after successfully execution of pagemethod on server side  
}

 function OnFailedID(error, methodName) {
        if (error !== null) {
           alert(error.get_message());
        }
    }

CS file :

CS文件:

   [WebMethod(enableSession: true)]
    public static returntype getValue(parameter type parameter1,parameter type parameter2)
    {
        do what you want to do with these values.

    }

Hope it helps you.

希望对你有帮助。

回答by Zoya

This is the javascript and aspx page

这是 javascript 和 aspx 页面

<script language="Javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


<script language="Javascript" type="text/javascript" src="http://api.easyjquery.com/easyjquery.js"></script>

<script language=Javascript>
    function setup_ip(json) {
        var htmlx = " Your IP Address: <b>" + json.IP;
        htmlx += "</b> | Country: " + json.countryName;
        var s = " | City: " + json.cityName + " / " + json.regionName;


      $("#hdn").val(s);


        if (json.cityName != "Unknown" || json.regionName != "Unknown") {
            htmlx += " | City: " + json.cityName + " / " + json.regionName;

           s = " | City: " + json.cityName + " / " + json.regionName;
        } else {
            htmlx += " | Your Time: " + json.localTimeZone;
        }




    }

    $(document).ready(function() {


        EasyjQuery_Get_IP("setup_ip", "full");

    });



function testValue() {
    $('#hdn').val();
}
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Release">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpnlHidden" runat="server">
    <ContentTemplate>
        <input runat="server" type="hidden" id="hdn" value="0" />
    </ContentTemplate>
</asp:UpdatePanel>
    <div class="inner">
<p class="welcome-message">
<a ><href="http://www.easyjquery.com/detect-get-clients-ip-address-country-using-javascript-php/"id="topid" title="Javascript, PHP jQuery API Detect Clients IP Address and Country - Geo Location"   ></a>

                <asp:TextBox ID="loc" runat="server"></asp:TextBox>

                </p>

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="setup_ip(json);" onclick="Button1_Click" />

            </div>

    </div>
    </form>
</body>
</html>

this is .cs code

这是 .cs 代码

protected void Page_Load(object sender, EventArgs e)
    {


        loc.Text = hdn.Value;
    }


  protected void Button1_Click(object sender, EventArgs e) 
{ 
string str = hdn.Value; 
}

回答by nbrooks

You can post data to the server using an ajax request. This is fairly straightforward since you are already using jquery. See api ref http://api.jquery.com/jQuery.ajax/.

您可以使用 ajax 请求将数据发布到服务器。这相当简单,因为您已经在使用 jquery。请参阅 API 参考http://api.jquery.com/jQuery.ajax/

$.ajax({
    type: "POST",
    url: "Page.aspx/method_name",
    data: { name: "some data", id: "some more data" }
}).done(function( msg ) {
    alert( "Data Saved: " + msg );
});

For this example, in your code-behind for Page.aspx you would have a method named method_name, which takes two parameters: string name, string id. That method would be decorated with the [WebMethod]attribute. Then you can use these however you like in that method.

对于此示例,在 Page.aspx 的代码隐藏中,您将有一个名为 method_name 的方法,它接受两个参数:字符串名称、字符串 id。该方法将使用该[WebMethod]属性进行修饰。然后您可以在该方法中随意使用这些。