简体   繁体   中英

Access a class from ASPX Code behind page using javascript

Im trying to access a class from code behind in javascript but I am getting the error saying it does'nt exist in this context. This has worked for me before this way.

Here is my code: Code Behind:

public class ReviewData
{
    public int NumberOfReviews { get; set; }
    public double AvgReviewScore { get; set; }
}

This variable has been populated further down

Here is my javascript:

<script type="text/javascript">
   var reviewData = "<%=ReviewData%>"
</script>

You'll have to use JSON.Net to serialize your class into a JSON string. Inside your class, create a method called "Serialize()" that returns a string and serializes itself.

In the Javascript, you could then write something like: var reviewData = "@ReviewData.Serialize()"

From there, you may have to use Javascript to parse it back into an object from a string... But you can't pass an actual C# class to Javascript. The best you can do is JSON.

Also, this won't work unless you have an object reference of ReviewData in your codebehind.

Brandon Millers answer is correct if you need to use a list of objects as an array. But if you want to access a single property of a class, you can do this. Declare it as a public variable

public ReviewData reviewData;

protected void Page_Load(object sender, EventArgs e)
{
    reviewData = new ReviewData();
    reviewData.NumberOfReviews = 5;
}

Now you can access the properties of the variable reviewData on the aspx.

<script type="text/javascript">
    var reviewData = '<%=reviewData.NumberOfReviews%>';
</script>

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