1

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

Community
  • 1
  • 1
rahularyansharma
  • 11,156
  • 18
  • 79
  • 135
  • `p` is the name of the variable, which you're calling `jsobject` in your JS. You should be able to use `jsobject.productId` and `jsobject.productName` if I understood correctly how this library works. – Dek Dekku May 22 '13 at 06:55

2 Answers2

2

The scope of your variable p is not right.

public partial class _Default : System.Web.UI.Page
{
    public product p;

    protected void Page_Load(object sender, EventArgs e)
    {
        p = new product();
        p.ProductId = 1;
        p.productName = "t-shirt";

    }

    public class product
    {
        public int ProductId { get; set; }
        public string productName { get; set; }
    }
}
Raimond Kuipers
  • 1,146
  • 10
  • 18
1

You can not access local variables of a function in scriptlets define a public property or data member.

public product p {get; set;}
protected void Page_Load(object sender, EventArgs e)
{    
    p = new product()
    p.ProductId = 1;
    p.productName = "t-shirt";
}
Adil
  • 146,340
  • 25
  • 209
  • 204