问题
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.
回答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).
回答2:
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;
}
来源:https://stackoverflow.com/questions/12786199/access-viewstate-eventvalidation-in-c-sharp