I want to use a object which is created in c# class in javascript
. I know i can use json library to convert my server side object to JSON
object so that it can be use in javascript
.
I have downloaded the Newtonsoft.Json
library for this . i have following aspx.cs
page code
using Newtonsoft.Json;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
product p = new product();
p.ProductId = 1;
p.productName = "t-shirt";
}
public class product
{
public int ProductId { get; set; }
public string productName { get; set; }
}
}
and for aspx
page i am using following code for javascript
to access that p object value .
<%@ Import Namespace="Newtonsoft.Json" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
var jsobject = <%= JsonConvert.SerializeObject(p) %>;
function myfunction (){
//work with object
alert('Hi');
}
</script>
</asp:Content>
when i try to build this its generate following exception
The name 'p' does not exist in the current context
i just want to use p id and name in my javascript code.
I have taken initially reference from this answer