1

Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function

JavaScript function:

function IsAgentInProgram()
{
    var optStatus = "<%=AgentOptInStatus%>";

    if (optStatus == "True")
        alert("You are opted in!");
    else
        alert ("You are opted OUT");
}

C# code behind

public bool AgentOptInStatus;

private void Page_Load(object sender, System.EventArgs e)
{
    this.AgentOptInStatus = true;

}

This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"

Am I missing something?

2
  • you can set to input the prop value and read it with js. Commented Feb 12, 2019 at 13:03
  • @RA19 this is what you are looking for stackoverflow.com/questions/1465732/… javascript is client side and c# is server side pretty big difference in variable declaration. Commented Feb 12, 2019 at 13:06

1 Answer 1

1

You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.

<asp:HiddenField ID="hdnfldVariable" runat="server" />

JS:

<script type="text/javascript">
        var somefunction = function () {
            var hdnfldVariable = document.getElementById('hdnfldVariable');
            hdnfldVariable.value = 'value from javascript';
        }
    </script>

c# :

string selected = hdnfldVariable.Value.ToString();

Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.

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.