How to run javascript function before writing back asp.net button?

I am using Javascript to create a DIV element and open a new page using onclientclick. This works great. Now I need to write it from the server side, and this element must be created before it is sent back.

How to get javascript to execute before writeback?

Currently, I have to click the button twice, because the item does not exist, to write too on the first click.

To be clear, I need this to be executed before the β€œOnClick” button.

Update: It looks like the Javascript function is called before the postback, but the item is not updated until I launched the second postback. Hmm

Update: Unfortunately, this is a little more complicated than that.

I am creating a div tag in javascript to open a new window. Inside the div tag, I use the data binding syntax <% = Preview%> so that I can access this element on the server side. From the server side, I embed the code.

I think it might be a chicken egg problem, but not sure.

UPDATE!

This is not Javascript that does not work in the first place. This is a data binding mechanism that reads an empty variable before I can set it.

Hmm

+5
source share
4 answers

you do not need to rely on server controls to perform postbacks in asp.net. you can get more precise control over your application by sending it from javascript whenever you are ready.

auto , __doPostback (.....), , .

. <button onclick="foo()" /> , , __doPostback.

asp.net Page.GetPostbackClientEvent( , , ) http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx

+1

. ?

Javascript

function stuffYouWantToDo(){
  //do your stuff
  //then submit the .NET form
  document.forms[0].submit();
}

.NET

<asp:button ID="Button1" onClientClick="return false;stuffYouWantToDo();"/>

, , , , . false stuffYouWantToDo .

0

If you want to use jquery, you can do the following:

$(document).ready(function() {

    var execScript = $(".myButton").attr("href").replace("javascript:", "");

    $(".myButton").attr("href", "#").click(function() {
        // Add before click logic here

        eval(execScript);
    });
});
0
source

Could you just add a custom validator somewhere in your form?

-1
source

All Articles