0

In c# code behind i am creating an object and try to access that in front-end javascript. but it is always getting instantiate value but not the object value; Please see the code below:

public class Product
{
    public String[] Sizes { get; set; }
    public decimal Price { get; set; }
    public DateTime Expiry { get; set; }
    public string Name { get; set; }
}

public partial class _Default : System.Web.UI.Page
{
    public string sJSON = "shuvra";

    public JavaScriptSerializer javaSerial = new JavaScriptSerializer();

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Btn2_Click(object sender, EventArgs e)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        Product product = new Product
        {
            Name = "Apple",
            Expiry = new DateTime(2008, 12, 28),
            Price = 3.99M,
            Sizes = new[] { "Small", "Medium", "Large" }
        };

        var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        sJSON = oSerializer.Serialize(product);

        JavaScriptSerializer ser = new JavaScriptSerializer();

        //ser.Serialize(arrayMarker, jasonSerialize); 

        sb.AppendLine("markicons();");

        ScriptManager.RegisterStartupScript(up_IFASelected, typeof(UpdatePanel), this.ClientID + "_LoadMap", sb.ToString(), true);
    }
}

The javascript code:

 function markicons() {
        initialize();

        var a = JSON.parse('<%= this.javaSerial.Serialize(this.arrayMarker) %>');

        var b = eval('<%=this.sJSON%>');
}

The value 'b' is always shuvra but not the assigned value. How can i fix it?

4
  • Have you tried to directly inject the JavaScript into the page? The DOM will need to be parsed, so you can just print out the JS object into a variable without eval. Commented Jun 11, 2013 at 11:37
  • I need this value in javascript json variable.
    – Shuvra
    Commented Jun 11, 2013 at 11:39
  • The value probably isn't persisting between postbacks. I'd recommend using a hidden field instead of a public property. Example: stackoverflow.com/questions/1548421/…
    – valverij
    Commented Jun 11, 2013 at 12:23
  • I have solve it. i add sb.AppendLine("list =" + sJSON + ";"); before adding javascript function with sb. and declare list as a variable in javascript.
    – Shuvra
    Commented Jun 11, 2013 at 14:54

0

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.