Question

My .NET skills aren't great, but I'm stumped by a little issue and I can't find anything that explains this in a way I understand. Basically I'm trying to pre-populate a form with current values from a CMS, and have those values able to be updated when the form is submitted. It's essentially just an 'edit' facility for part of a website.

I have a usercontrol which contains some form inputs like this:

<label for="">Raised by</label>
<asp:TextBox ID="RaisedBy" runat="server"></asp:TextBox>

I then have a code-behind page which pulls values from a CMS and populates this form with the values already stored for this record, like this:

protected void Page_Load(object sender, EventArgs e)
{
    // ...Some logic here gets the node from the CMS and I can pull property values from it.  This part works fine.
    string raisedBy = node.GetProperty("raisedBy").ToString();

    // Populate form input with value from CMS. This works.
    RaisedBy.Text = raisedBy;
}

So this is fine. But when the form is submitted it calls the following code:

protected void edit_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        // Get edited value of input field
        string RaisedByVal = RaisedBy.Text;

        // Do some logic here to set up the CMS to be able to save the property - this works although it uses the original value of the form not the modified value if the user has changed it.
        pageToEdit.getProperty("raisedBy").Value = RaisedByVal;
    }
}

The problem is that the original form values are being saved back to the system rather than the modified values if the user has edited them.

Can anyone suggest what I'm doing wrong and how to get the modified values to be used rather than the original values?

Many thanks.

Was it helpful?

Solution

You have to check whether it is Postback or not in Page_Load() method:

So if you don't do this then on edit button click it will 1st call the Page_Load() and will again reset the original value. Later it will call the Edit click method and you will still see the original data.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // ...Some logic here gets the node from the CMS and I can pull 
            property values from it.  This part works fine.
            string raisedBy = node.GetProperty("raisedBy").ToString();

            // Populate form input with value from CMS. This works.
            RaisedBy.Text = raisedBy;
        }
    }

OTHER TIPS

Typically I found the answer right after posting! :)

I needed to wrap the 'pre-populate form values' logic inside a:

if (!IsPostBack)
{
}

block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top