简体   繁体   中英

ASP.Net How do I execute a dynamic JavaScript and prevent a postback

I have and ASP button and 2 Labels.

<asp:Button runat="server" ID="btnHide" />
<asp:Label runat="server" ID="lblName"></asp:Label>
<asp:Label runat="server" ID="lblPosition"></asp:Label>

I have created a dynamic JS script.

string jsbtnHide = @"document.getElementByID('" + lblName.ClientID + @"').value = '';
document.getElementByID('" + lblPosition.ClientID + @"').style.display = 'none';";

I assign the script to the button. I've tried both "OnClick" and "OnClientClick".

btnHide.Attributes.Add("OnClick", jsbtnHide);

However I cannot get the script to execute successfully and without a postback. I've tried adding OnClientClick="return false;" both dynamically and to the ascx file. Dynamically seems to be ignored, though it appears correct in FireBug. OnClick doesn't seem to prevent the Postback. When the script does run, lblName doesn't change to '', haven't got this to work once.

What am I doing wrong? I've been at this for days :(

You can use a good trick just change your click code to this

string jsbtnHide = @"document.getElementByID('" + lblName.ClientID + @"').value = '';
document.getElementByID('" + lblPosition.ClientID + @"').style.display = 'none';return;";

add return to end of the code preventing from calling postback event

Try wrapping the JS code you intend to execute in a JS function and then wire-up the button with the function and an additional statement of return false.

Something like this:

public string DynamicJSCode; //Page level

//Page_Load

    DynamicJSCode = @"function doSomeWork(){document.getElementById('" + lblName.ClientID + @"').innerText= '';
    document.getElementById('" + lblPosition.ClientID + @"').style.display = 'none'; return false;}";

You can then embed the JS above in your page using properties (or any other means).

<script type='text/javascript' language='javascript'>
<%= DynamicJSCode %>
</script>

And then wireup the function to the button as below:

btnHide.Attributes.Add("onclick", "return doSomeWork();");

To prevent button controls to not postback you will have to use the return; call (without any doubt).

This would be slightly more maintainable (to my understanding) and then you would also not need the additional button event handler attachment in the code behind. In the markup itself you could then assign the JS function call to the OnClientClick event and the code that executes would always be dynamically generated.

<asp:Button runat="server" ID="btnHide" OnClientClick='doSomeWork();return false;' />

It is always recommended to write code with better maintainability irrespective of the size or importance of the functionality.

Hope it helps!

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