user1074474
user1074474

Reputation: 461

How to assign ASP.NET hidden field value to JavaScript variable?

Following is the code snippets taken from http://pietschsoft.com/post/2011/09/09/Tag-Editor-Field-using-jQuery-similar-to-StackOverflow.aspx

// pre-selected tags
values: [
    'javascript',
    'css',
    'jquery'];  

I want to assign values with some hidden field or C# variable, please help as I don't have expertise with JavaScript/jQuery.

Upvotes: 3

Views: 2960

Answers (2)

Zachary
Zachary

Reputation: 6532

You can create a public property and use it in your HTML like the following...

C# (Added per/comments)

public string Choices { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    string[] choices = new string[] { "'Choice 1'", "'Choice 2'", "'Choice 3'" };
    Choices = String.Join(",", choices);
}

JavaScript

<script type="text/javascript">
    var values = [<%= Choices %>];
</script>

NOTE: I put single quotes around the values since JavaScript requires the them to recognize the value as part of a string array ( Valid = ['value','value'] / Invalid = [value,value] ).

Upvotes: 3

Brent Anderson
Brent Anderson

Reputation: 966

hidden:

values: [
        $('hidden1').val(),
        $('hidden2').val(),
        $('hidden3').val()];

or c# (mvc):

values: [
        '@model.var1',
        '@model.var2',
        '@model.var3'];

Upvotes: 0

Related Questions