Search code examples
asp.netwebformsviewstate

Found 2 elements with non-unique id #__VIEWSTATE


I am working on a legacy ASP.NET application that renders two forms on a single web page. Each form implements its own __VIEWSTATE field.

Since Chrome v63 duplicate field names throw an error in the console:

Found 2 elements with non-unique id #__VIEWSTATE

I don't have the luxury of rewriting the application to remove the duplicated forms. Is there another way to rename the __VIEWSTATE fields, or some other work around?


Solution

  • In Page class there are two methods that saves and loads view state. By overriding these two methods and set them to use another hidden filed you can rename __VIEWSTATE for that page.

    Here's how you can do it:

    public partial class SamplePage : Page
    {
        const string ViewStateHiddenFiledName = "_VIEWSTATE_Page1";
    
        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            LosFormatter los = new LosFormatter();
            StringWriter writer = new StringWriter();
    
            los.Serialize(writer, viewState);
    
            string serilizedViewState = writer.ToString();
    
            ClientScript.RegisterHiddenField(ViewStateHiddenFiledName, serilizedViewState);
        }
    
        protected override object LoadPageStateFromPersistenceMedium()
        {
            string serilizedViewState = Request.Form[ViewStateHiddenFiledName];
            if (serilizedViewState != "")
            {
                LosFormatter los = new LosFormatter();
                return los.Deserialize(serilizedViewState);
            }
            return null;
        }
    }