2

In ASP.NET, is it possible to get the values of __VIEWSTATE and __EVENTVALIDATION hidden fields into a variable in C# (server side) in, let's say, overriding the Render method?

I have tried:

protected override void Render(HtmlTextWriter writer)
{
    StringBuilder stringBuilder = new StringBuilder();
    StringWriter stringWriter = new StringWriter(stringBuilder);
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

    base.Render(htmlWriter);
    string temp = stringBuilder.ToString();
}

This gives me the entire ASP.NET output. We can get the values by using a string function, but I did not find it a very clean solution. Is there a better way to do this?

What I actually want is the values of __VIEWSTATE & __EVENTVALIDATION when the first request is made and not after the postback is done. That is when the output stream if formed when the first request is made.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yuvi Dagar
  • 649
  • 2
  • 11
  • 20
  • 1
    They should be available in the Request.Form collection. Have you tried Request.Form["__VIEWSTATE"] and Request.Form["__EVENTVALIDATION"] – Yiğit Yener Oct 08 '12 at 17:06
  • Yigit Yener, thank you for the answer. Actually want I is a bit different. I have rephrased my question. – Yuvi Dagar Oct 09 '12 at 04:41

2 Answers2

1

If you look at the Page class using Reflector, you'll see these hidden fields are created during the render phase (look at the methods RenderViewStateFields and EndFormRenderHiddenFields).

You could probably get at some/all of the data using reflection (e.g. the internal property Page.ClientState).

But I don't think there is a clean solution (though to be honest I don't really understand what you're trying to achieve).

Joe
  • 122,218
  • 32
  • 205
  • 338
  • Joe, thanks for the reply. I am trying to restructure the output a bit, that is why I need access to the hidden fields. I will have a look into the methods mentioned above and get back. – Yuvi Dagar Oct 09 '12 at 14:09
  • Ok, I was able to get the value of __VIEWSTATE by using the above methods. I still have no idea regarding __EVENTVALIDATION ... any thoughts? – Yuvi Dagar Oct 10 '12 at 04:14
1

To get the event validation you should use HTML Agility Pack.

var eventValidation = HapHelper.GetAttributeValue(htmlDocPreservation, "__EVENTVALIDATION", "value");

public static string GetAttributeValue(HtmlDocument doc, string inputName, string attrName)
{
    string result = string.Empty;

        var node = doc.DocumentNode.SelectSingleNode("//input[@name='" + inputName + "']");
        if (node != null)
        {
            result = node.Attributes[attrName].Value;
        }


    return result;
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
jdMiami
  • 51
  • 4
  • jdMiami, thanks for the answer. I had asked this question a long time ago. Let me verify and get back to you. – Yuvi Dagar Feb 19 '14 at 17:14