JSON variable not updating on postback

126 Views Asked by At

I have a form to edit database values. I register a json variable using ClientScriptManager.RegisterClientScriptBlock on page load and then use it to check for changes to the form and prompt the user to save. In the save button click event I then re-execute the code that registers the json variable so that it contains the changes the user just saved.

The problem I've run into is the json variable is not updating to reflect the changes to the form after the postback. Only after refreshing the page does the json varable update.

protected void Page_Load(object sender, EventArgs e)
{
    Property p = Property.GetPropertyById(id);
    PopulateForm(p);
    CreateJson(p);
}

protected void btnSave_Click(object sender, EventArgs e)
{
    Property p = Property.GetPropertyById(id);
    p.Price = txtPrice.Text.Trim();

    p.Save();
    CreateJson(p);
}

private void CreateJson(Property p)
{
    StringBuilder JSONtext = new StringBuilder();
    JSONtext.Append("<script type='text/javascript'>");
    JSONtext.Append("var property = ");
    JSONtext.Append("{");
    JSONtext.Append("\"price\":\"");
    JSONtext.Append(p.Price.ToString());
    JSONtext.Append("};");
    JSONtext.Append("</script>");

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsonVariable", JSONtext.ToString());
}

Is what I'm trying to do even possible?

1

There are 1 best solutions below

1
Mad Dog Tannen On BEST ANSWER

Give this a try

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack == false)
    {
      Property p = Property.GetPropertyById(id);
      PopulateForm(p);
      CreateJson(p);
    }
}

protected void btnSave_Click(object sender, EventArgs e)
{
    Property p = Property.GetPropertyById(id);
    p.Price = txtPrice.Text.Trim();

    p.Save();
    CreateJson(p);
    PopulateForm(p);
}

It executes PopulateForm(p) after you've created the json, and in the Page_Load it only runs if it is not a PostBack