2

I would like to assign a value from codebehind to an angularjs variable. What is the best way to do this. (say I have a variable var UserInfo in app.js).

If the page is Default.aspx, I would do this in Default.aspx.cs for a JS variable. ASPX:

<script>
    var idSeparator;
</script>

Code Behind:

protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {

        }
        AssignValueToJavascriptVariable();           
    }

  private void AssignValueToJavascriptVariable()
    {
   string idSeparator = string.Format("var idSeparator = '{0}';", Constants.ID_SEPARATOR);
   if (!Page.ClientScript.IsClientScriptBlockRegistered("IdSeparator"))
     {
      Page.ClientScript.RegisterClientScriptBlock(this.GetType(),   
       "IdSeparator", idSeparator, true);
        }     
    }
1
  • 1
    your angular code can access a global variable also. Commented Jan 22, 2015 at 16:33

1 Answer 1

3

Another way would be to use properties and from Default.aspx page call it e.g.

public string idSeparator {get { return "test"; }}

In aspx page:

<script type="text/javascript">
       var idSeparator = '<%=idSeparator %>';
 </script>

You can have your property to not be read-only and later on set the property value if you require that.

Or alternatively you can use Asp.net hidden fields.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.