简体   繁体   中英

Variable from javascript function in aspx page accessible in c# code in same javascript function

My code in aspx page is:

<script type="text/javascript">       
    function MenuItem_Click(itemId) {
        <%                 
            MyAspLogger("Clicked on item: {0}", itemId); 
        %>
    }
</script>

I don't know how to access "itemId". I know that from other side - accessing c# variable in aspx code it is possible. But I don't know if is possible access javascript variable in c# code include in same javascript function.

Thank you for your help.

I guess you are tryingto get the clicked menu ids, and then log all clicked menu item?

1- To get the menu id,

Pass the menu object using keyword "this" to the function handling the click (MenuItem_Click).

<a id='menu_1 onclick='return MenuItem_Click(this);'>Click Me!</a>
<script type="text/javascript">
function MenuItem_Click(me) {
  alert(me.id); // The Id of menu clicked.
   // Do Whatever you want with the id now.
   .
   .
   .
 }
</script>

2- Logging clicked menu id

You have 2 options actually ... use a web-service call each time a menu clicked (which I don't recommend)

OR

Use a variable to store the clicked menu ids Or a hidden variable.

<script type="text/javascript">
function MenuItem_Click(me) {
    var hdnMenuLog = document.getElementById('hdnMenuLog');
    hdnMenuLog.value = hdnMenuLog.value + '|' + me.id;
 }
</script>

Hope this helps!

You can not access javascript variable value in server side code until you do postback and send asnc call using ajax. Asp.net generates html and javascript code from server side and sends response to client ie browser.

To access javascript variable value after postback you can assign it to some hidden field that is made server accessible and access it on server side code. This is how asp.net maintains ViewState .

I tried

<asp:Label CssClass="helperLabel" runat="server" Visible="False">Test</asp:Label>

<script type="text/javascript">
function MenuItem_Click(item) {
        // Setup
        $(".helperLabel").html("asdf");
        <%
            MyAspLogger("Clicked on item"); 
        %>
</script>

in code behind I have

protected void MyAspLogger(string logMessage)
{
        MyLogger.Debug(logMessage + "/" + helperLabelId.Text);
}

It's working fine but 2 other issue.

Text is not change on server side but only on client side(saw that after removed Visible attribute from asp control).

And also I found that MyAspLogger method is called on page load not after click event.

What I need is grabb itemId and log that via my Logger method from code behind.

Thank you.

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