Why can't I update HiddenFields on PostBack?

This is my code:

private string[] MesiSelezionati;

protected void Page_Load(object sender, EventArgs e)
{
    MesiSelezionati = new string[] { "2", "4" };
    UpdateMesi();
}

override protected void OnInit(EventArgs e)
{
    for (int i = 1; i <= 12; i++)
    {
        HtmlGenericControl meseItem = new HtmlGenericControl("a") { InnerHtml = "mese" };
        meseItem.Attributes.Add("href", "javascript:void(0);");

        HiddenField hf = new HiddenField();
        hf.Value = "0";
        hf.ID = "idMese_" + i.ToString();

        meseItem.Controls.Add(hf);

        panelMesi.Controls.Add(meseItem);
    }

    base.OnInit(e);
}

private void UpdateMesi()
{
    foreach (HtmlGenericControl a in panelMesi.Controls.OfType<HtmlGenericControl>())
    {
        HiddenField hf = a.Controls.OfType<HiddenField>().LastOrDefault();
        if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault()))
        {
            hf.Value = "1";
            a.Attributes.Add("class", "box-ricerca-avanzata-item link-box selected");
        }
    }
}

When I call the page, everything is fine! The problem is that I am invoking the same page (like postback) thanks to asp: LinkButton. I get a System.NullReferenceExceptionon if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault())).

It seems that the HiddenField lines 2 ° and 4 ° (which corresponds to position c MesiSelezionati = new string[] { "2", "4" };) is zero. What for? And how can I fix this?

EDIT: Code for Mark M

HtmlGenericControl optionBox = new HtmlGenericControl("div");
optionBox.Attributes["class"] = "option-box";

HtmlGenericControl optionBoxItem = new HtmlGenericControl("a") { InnerHtml = "&nbsp;" };
optionBoxItem.Attributes.Add("href", "javascript:void(0);");
optionBoxItem.Attributes.Add("class", "option-box-item");

HtmlGenericControl optionBoxTesto = new HtmlGenericControl("a") { InnerText = Categoria.Categoria };
optionBoxTesto.Attributes.Add("href", "javascript:void(0);");
optionBoxTesto.Attributes.Add("class", "option-box-testo");

HiddenField hf = new HiddenField();
hf.Value = "0";
hf.ID = "categoria_" + Categoria.UniqueID;

optionBox.Controls.Add(optionBoxItem);
optionBox.Controls.Add(optionBoxTesto);
optionBox.Controls.Add(hf);

panelCategorieGuida.Controls.Add(optionBox);
+3
source share
2 answers

You can update hidden fields during postback, but not before downloading. When OnInit is executed, the controls are not populated using the request and view state values. Your updates will be overwritten.

EDIT: - .

  • InnerHtml (InnerHtml = "mese") OnInit. ViewState["innerhtml"] = "mese".
  • css ViewState, ViewState .

css, HtmlContainerControl.LoadViewState( InitComplete PreLoad). LoadViewState , ViewState [ "innerhtml" ] , ( Controls.Clear()) LiteralControl, InnerHtml, .

, InnerHtml - HtmlContainerControl, ViewState.

; , InnerHtml , LiteralControl .

+3

- ? , , AJAX? .

0

All Articles