简体   繁体   中英

Calling JS function from ASP.NET codebehind

I have two javascript functions in my aspx page. They use some fabric.js functions.

function saveCanvas() {
    js = JSON.stringify(canvas.toDatalessJSON());
    $get('<%= txtJSON.ClientID%>').value = js;

}
function loadCanvas() {
    js = $get('<%= txtJSON.ClientID%>').value;
    canvas.clear();
    canvas.loadFromDatalessJSON(js);
    canvas.renderAll();
}

And in the codebehind:

 Protected Sub SaveJSON()
    Dim scriptKey As String = "123"
    Dim javaScript As String = "<script type='text/javascript'>saveCanvas();</script>"
    ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
 End Sub

Protected Sub LoadJSON()
    Dim scriptKey As String = "456"
    Dim javaScript As String = "<script type='text/javascript'>loadCanvas();</script>"
    ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
End Sub

Now my question: Why does loadCanvas work while saveCanvas does not? txtJSON is not populated with the JSON-string. Calling the saveCanvas function from the aspx page works fine.

The problem is that you call saveCanvas after the postback is done and at that point the canvas data is long gone.

If you have a button "Save" then you need to call saveCanvas when it is clicked so that the data is saved before the browser posts the page back to the server:

<asp:Button runat="server" Text="Save" OnClickClick="saveCanvas()" />

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