简体   繁体   中英

List.count always resetting to 0 after adding element

I am creating a Web Form using visual Studio 2010 and I have a .aspx page that grabs some user input and saves it to a database. There are two buttons on the page, one for the user to "save" values (should be added to the list here) and the second to actually save them to the database in the proper format. My code is below:

namespace TabletApplication.HomePages
{
    public partial class Record : System.Web.UI.Page
    {
        List<ReadingModel> paramList;

        protected void Page_Load(object sender, EventArgs e)
        {
            paramList = new List<ReadingModel>();
        }



        public class ReadingModel
        {
            public int paramId { get; set; }
            public string value { get; set; }
            public Boolean pass { get; set; }
            public string comment { get; set; }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            // Get an instance of the Button
            Button UpdateButton = (Button)sender;
            // Get the ID of the current record from the CommandArgument
            int intID = Convert.ToInt32(UpdateButton.CommandArgument);
            bool goodValue;
            using (TabletApplicationEntities serverContext = new TabletApplicationEntities())
            {
                // Get the value and comment
                TextBox Reading =
                    (TextBox)UpdateButton.Parent.FindControl("txtReading");
                TextBox Comment =
                    (TextBox)UpdateButton.Parent.FindControl("txtComment");

                //Get min and max values
                Label Min = (Label)UpdateButton.Parent.FindControl("minValLabel");
                Label Max = (Label)UpdateButton.Parent.FindControl("maxValLabel");
                double minVal = Convert.ToDouble(Min.Text);
                double maxVal = Convert.ToDouble(Max.Text);
                int readingVal = -1;

                try
                {
                    readingVal = Convert.ToInt32(Reading.Text);
                    goodValue = true;
                }
                catch
                {
                    Reading.Text = "Invalid entry: Must enter a number";
                    Reading.BackColor = System.Drawing.Color.Red;
                    Reading.ForeColor = System.Drawing.Color.Blue;
                    goodValue = false;
                }

                if (goodValue)
                {
                    // Update the record
                    ReadingModel Result = new ReadingModel();
                    Result.comment = Comment.Text;
                    Result.value = Reading.Text;
                    Result.paramId = intID;
                    if (readingVal > minVal && readingVal < maxVal && readingVal >= 0)
                    {
                        Result.pass = true;
                    }
                    else if (readingVal < minVal || readingVal > maxVal)
                    {
                        Result.pass = false;
                    }
                    else
                    {
                        Reading.Text = "UNKNOWN ERROR: Try again";
                        Reading.BackColor = System.Drawing.Color.Red;
                        Reading.ForeColor = System.Drawing.Color.Blue;
                    }
                    paramList.Count();
                    paramList.Add(Result);
                    paramList.Count();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (TabletApplicationEntities serverContext = new TabletApplicationEntities())
            {
                // Create a new Reading
                foreach (var para in paramList)
                {
                    Reading objReading = new Reading();
                    // Set values
                    objReading.ParamID = para.paramId;
                    objReading.comment = para.comment;
                    objReading.date = System.DateTime.Now;
                    objReading.pass = para.pass;
                    objReading.reading1 = para.value;

                    // Add object
                    serverContext.Readings.AddObject(objReading);
                }

                // Save changes
                serverContext.SaveChanges();
                paramList.Clear();
            }
        }
    }
}

When the user hits the first button, the btnUpdate_Click function runs properly, and adds the new Result to paramList . With breakpoints on the two paramList.Count() I can see that the count is 0 before the result is added, and 1 afterwards, like it should be. When the save button is pressed, however, the btnSubmit_Click function runs and completely skips over the for loop because the count of paramList is 0 again. Any Ideas?

EDIT 1:

I tried adding a ViewState to the Page_Load, but I believe it's not working because List is not "serializeable" but i don't know how to fix it. This is what I added:

List<ReadingModel> paramList;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ViewState["paramList"] != null)
            {
                paramList = (List<ReadingModel>)ViewState["paramList"];
            }
            else
            {
                paramList = new List<ReadingModel>();
            }
        }

paramsList needs to be persisted between postbacks. You can store the list in the Session or ViewState. Doing so will allow it to live longer than the request.

you can create a property on your page something like (not tested):

public List<ReadingModel> paramsList
{
    get 
    {
        if(ViewState["paramsList"] == null)
            ViewState["paramsList"] = new List<ReadingModel>();

        return ViewState["paramsList"] as List<ReadingModel>;
    }
    set 
    {
         ViewState["paramsList"] = value;
    }
}

paramList is a private variable on the page an will be reset whenever the page is posted back. In order to persist paramList on postback you need to store it in a session variable. So change:

 paramList.Add(Result);

to:

  ((List<ReadingModel>)Session["paramList"]).Add(Result)

You can encapsulate the session in a public property like this:

public List<string> paramList 
    {
        get
        {                
            if (Session["paramList"] != null)
            {
                return (List<string>)Session["paramList"];
            }
            else
            {
            Session["paramList"] = new List<string>();
            return (List<string>)Session["paramList"];
            }
     }                
        set { Session["paramList"] = value; }
    }

When you click your button, the values will be added to this list, accessed through the public property. The values added to the list will not be removed when the page does a postback.

    protected void Button1_Click(object sender, EventArgs e)
    {
        paramList.Add("test");
    }

(i'm using a list of strings as an example, but i assume you get the idea)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM