Create javaScript variable in code behind of asp.net

前端 未结 4 2151
不知归路
不知归路 2020-12-16 19:39

How do I register a Javascript variable on the server side (backend) and access it on the client side (Javascript file), without a hidden field, Literal, etc.?

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 19:53

    You can use the RegisterClientScriptBlock-Function from the Page's ClientScriptManager.

    Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "initMyClientVariable", "var myClientVariable=null;", True)
    

    EDIT: according to your new informations, that you want to register a client array, use ClientScriptManager's RegisterArrayDeclaration Method.

    VB.Net example:

    Dim myArrayValue As String = """1"", ""2"", ""text"""
    Page.ClientScript.RegisterArrayDeclaration("myClientArray", myArrayValue)
    

    According to the new information in my comments that you need access to that variable from an external js-file: you should pass the js-array as argument to the function in the js-file. For example:

    callFunctionInJsFile(checkBoxes);
    

提交回复
热议问题