简体   繁体   中英

how to pass javascript variable to embedded Server Side code ASP.NET WebForm

let say i have a function like below in BAL.cs file

public static void xyz(string name)
{
    Response.Write("Hello "+name);
}

Let say i have a javascript variable x.

now i want to call the function from BAL.aspx file

<script>
   var x= "Tahmid";
   <%=BAL.xyz()%> // want to pass x as a parameter
</script>

在此处输入图片说明

this is in webform.

It seems like there is some sort of confussion here that I would like to help solve. Server code and client code are separated . When client code executes (such as javascript) the server has no way to know what happened so your server side code (code behind) is not aware of any changes. In order to have the javascript variable information on the code behind you'll need to send that variable value back to the server and one of the mechanisms is the one provided by user2952502 . I think in your case a postBack (using a submit or link button) would be more appropiate, right? I think you're trying to redraw the page based on something that the user did (since you're using javascript).

I think we should have some more information to understand the whole scope of your question and probably suggest you a better way to deal with it.

so you want to use windowfunctioname ? since javascript is clientside and asp is serverside you could create a list of calls with parameters.

<script type="text/javascript">
  var calls = [{exec: 'functionname', param : {name: 'Tahmid'}}];

   document.addEventListener('DOMContentLoaded', function () {
        c = calls.length;
        for (var i = 0; i < c; i++) {
            call = calls[i];
            window[call.exec](call.param);
        }
    });
</script>

I hope that was an answer that helps.

The question is not clear enough .

what are u trying to do ?

just to print a dynamic text u can do with javascript function..

if u have to use a server function please specify the platform u use : MVC / WebForms..

in MVC you can use jQuery Post:

<script>
var x = "value";
$.post('@Url.Action("Action","Controller")',{name : x});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM