FindControl() method for Dynamically Nested Controls on PostBack - asp.net

How do you get a specific nested control of dynamically created controls (i.e. the child of a dynamic control)? The FindControl() method does not work because it only deals with TopLevel dynamic controls I believe.

You need to recurse through your controls: (C# code)
public static Control FindControl(Control parentControl, string fieldName)
{
if (parentControl != null && parentControl.HasControls())
{
Control c = parentControl.FindControl(fieldName);
if (c != null)
{
return c;
}
// if arrived here, then not found on this level, so search deeper
// loop through collection
foreach (Control ctrl in parentControl.Controls)
{
// any child controls?
if (ctrl.HasControls())
{
// try and find there
Control c2 = FindControl(ctrl, fieldName);
if (c2 != null)
{
return c2; // found it!
}
}
}
}
return null; // found nothing (in this branch)
}

This is an extension method I've used in times past. I've found that using it as an extension method makes the code a little more expressive, but that's just preference.
/// <summary>
/// Extension method that will recursively search the control's children for a control with the given ID.
/// </summary>
/// <param name="parent">The control who's children should be searched</param>
/// <param name="controlID">The ID of the control to find</param>
/// <returns></returns>
public static Control FindControlRecursive(this Control parent, string controlID)
{
if (!String.IsNullOrEmpty(parent.ClientID) && parent.ClientID.Equals(controlID)) return parent;
System.Web.UI.Control control = null;
foreach (System.Web.UI.Control c in parent.Controls)
{
control = c.FindControlRecursive(controlID);
if (control != null)
break;
}
return control;
}

Related

Get reference of image button click event in gridview in http module

How do we pass the Click event of ImageButton inside a GridView to httpmodule
for linkbutton's i am doing this way:
if (request.Form.GetValues("__EVENTTARGET") != null)
{
//If it's a link button execute we can directley check for the params
if (request.Params.Get("__EVENTTARGET").Contains("xyz"))
{
//some Code
}
This is not working for ImageButton.
If you're trying to attach an event to a button within a gridview might I suggest in your base page on the prerender event parse through all gridviews on the page (use a recursive findcontrol algorithm) and look for any imagebuttons, if you find one you should then be able to attach an event to it.
EDIT:
I use something similar in the following:
public abstract class AmendmentPopUpWindow : BaseMasterPlanPage
{
// override this method if the correct save controls arent being hidden in the popups
public virtual IEnumerable<WebControl> SaveControls
{
get { return Controls.All().OfType<WebControl>().Where(c => c.ID.ToLower().Contains("save")); }
}
protected override void OnPreRender(EventArgs e)
{
if (WebConfiguration.Global_EnableAmendments && SystemVersion.HasValue)
{
foreach (var control in Controls.All())
{
if (control is RadioButton || control is TextBox || control is DropDownList || control is RadComboBox || control is CheckBox || control is CheckBoxList ||
control is RadEditor || control is RadTextBox || control is RadNumericTextBox)
{
var webControl = control as WebControl;
webControl.Enabled = false;
webControl.ForeColor = Color.Gray;
}
}
foreach (var saveControl in SaveControls)
saveControl.Visible = false;
}
base.OnPreRender(e);
}
EDIT: The .All() is an extension method defined as follows (stolen from here)
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
ImageButtons have an additional quasi-property in their names which identifies the mouse-coordinates (X and Y).
So to find the ImageButton's name your should iterate through posted parameters and found those which end with .x or .y:
foreach (string item in request.Form)
{
if (item.EndsWith(".x") || item.EndsWith(".y"))
{
var controlName = item.Substring(0, item.Length - 2);
// some code here
}
}
You could also cound this answer useful. It contains a more generic method to determine which control caused a postback.

How to use ASP.Net server controls inside of Substitution control?

while the method we use in Substitution control should return strings, so how is it possible to use a donut caching in web forms on a server control which should be rendered server side?
for example Loginview control?
UPDATE
This is now a fully working example. There a few things happening here:
Use the call back of a substitution control to render the output of the usercontrol you need.
Use a custom page class that overrides the VerifyRenderingInServerForm and EnableEventValidation to load the control in order to prevent errors from being thrown when the usercontrol contains server controls that require a form tag or event validation.
Here's the markup:
<asp:Substitution runat="server" methodname="GetCustomersByCountry" />
Here's the callback
public string GetCustomersByCountry(string country)
{
CustomerCollection customers = DataContext.GetCustomersByCountry(country);
if (customers.Count > 0)
//RenderView returns the rendered HTML in the context of the callback
return ViewManager.RenderView("customers.ascx", customers);
else
return ViewManager.RenderView("nocustomersfound.ascx");
}
Here's the helper class to render the user control
public class ViewManager
{
private class PageForRenderingUserControl : Page
{
public override void VerifyRenderingInServerForm(Control control)
{ /* Do nothing */ }
public override bool EnableEventValidation
{
get { return false; }
set { /* Do nothing */}
}
}
public static string RenderView(string path, object data)
{
PageForRenderingUserControl pageHolder = new PageForUserControlRendering();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");
if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("ViewFile: " + path + "has no data property");
}
}
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, result, false);
return result.ToString();
}
}
See these related questions:
Turn off page-level caching in a
user control
UserControl’s RenderControl is
asking for a form tag in (C#
.NET)
One thing Micah's answer left out is that the substitution function must be static, accept a HttpContext parameter, and return a string. See this msdn page for more info.
I've also extended Micah's helper class to be a little more flexible.
Markup
<asp:Substitution ID="Substitution1" MethodName="myFunction" runat="server" />
Implemenation
public static string myFunction(HttpContext httpContext){
ViewManager vm = new ViewManager();
//example using a Button control
Button b = new Button();
b.Text = "click me"; //we can set properties like this
//we can also set properties with a Dictionary Collection
Dictionary<string,object> data = new Dictionary<string,object>();
data.add("Visible",true);
String s = vm.RenderView(b,data); //don't do anything (just for example)
//we can also use this class for UserControls
UserControl myControl = vm.GetUserControl("~mypath");
data.clear();
data.add("myProp","some value");
return vm.RenderView(myControl,data); //return for Substitution control
}
Class
using System.IO;
using System.ComponentModel;
public class ViewManager
{
private PageForRenderingUserControl pageHolder;
public ViewManager()
{
pageHolder = new PageForRenderingUserControl();
}
public UserControl GetUserControl(string path)
{
return (UserControl)pageHolder.LoadControl(path);
}
public string RenderView(Control viewControl, Dictionary<string, object> data)
{
pageHolder.Controls.Clear();
//Dim viewControl As UserControl = DirectCast(pageHolder.LoadControl(Path), UserControl)
if (data != null) {
Type viewControlType = viewControl.GetType();
dynamic properties = TypeDescriptor.GetProperties(viewControl);
foreach (string x in data.Keys) {
if ((properties.Item(x) != null)) {
properties.Item(x).SetValue(viewControl, data[x]);
}
}
}
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, result, false);
return result.ToString();
}
private class PageForRenderingUserControl : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
// Do nothing
}
public override bool EnableEventValidation {
get { return false; }
// Do nothing
set { }
}
}
}
Thanks again to Micah for the code
I'm fairly certain you can't do this - the Substitution control will only allow you to insert a string into an outputcached page.
This makes sense if you think about the whole output of a server control, which could be a <table> that'll disrupt all your carefully crafted markup and/or something that requires a load of <script> injected into the page - whereas injecting a single string is something that's relatively straightforward.

How to validate against Multiple validation groups?

I have two validation groups: parent and child
I have an add button that needs to only validate the child validation group which is easily done. The save button needs to validate against the parent and child validation groups, both client side and server side. I think I know how to do it server side by calling the Page.Validate("groupname") method for each group, but how can it be done client side?
You should be able to accomplish this by creating a javascript function that uses Page_ClientValidate and then having the button call that function
<asp:Button ID="btnSave" Text="Save" OnClientClick="return validate()" runat="server" />
<script type="text/javascript">
function validate() {
var t1 = Page_ClientValidate("parent");
var t2 = Page_ClientValidate("child");
if (!t1 || !t2) return false;
return true;
}
</script>
The problem with CAbbott's answer is that validation errors that occur in the "parent" group will not be displayed after the call to validate the "child" group. The more minor problem with Oleg's answer is that validation of the "child" group will not occur until the "parent" group is ready.
All we really need to do to allow client-side validation of more than one group at the same time is to override the Javascript IsValidationGroupMatch method which determines whether or not a control is to be included in the current set being validated.
For example:
(function replaceValidationGroupMatch() {
// If this is true, IsValidationGroupMatch doesn't exist - oddness is afoot!
if (!IsValidationGroupMatch) throw "WHAT? IsValidationGroupmatch not found!";
// Replace ASP.net's IsValidationGroupMatch method with our own...
IsValidationGroupMatch = function(control, validationGroup) {
if (!validationGroup) return true;
var controlGroup = '';
if (typeof(control.validationGroup) === 'string') controlGroup = control.validationGroup;
// Deal with potential multiple space-delimited groups being validated
var validatingGroups = validationGroup.split(' ');
for (var i = 0; i < validatingGroups.length; i++) {
if (validatingGroups[i] === controlGroup) return true;
}
// Control's group not in any being validated, return false
return false;
};
} ());
// You can now validate against multiple groups at once, for example:
// space-delimited list. This would validate against the Decline group:
//
// Page_ClientValidate('Decline');
//
// while this would validate against the Decline, Open and Complete groups:
//
// Page_ClientValidate('Open Decline Complete');
//
// so if you wanted to validate all three upon click of a button, you'd do:
<asp:Button ID="yourButton" runat="server"
OnClick="ButtonSave_Click" CausesValidation="false"
OnClientClick="return Page_ClientValidate('Open Decline Complete');" />
If you call Page_ClientValidate(..) twice, only the last validation result will be shown and it can be OK while the first is not. So the second call should be made only if the first has returned true
<script type="text/javascript">
var parentOk= Page_ClientValidate('parent');
var childOk = false;
if (parentOk) {
childOk = Page_ClientValidate('child');
}
return parentOk && childOk;
</script>
Whatever way you do it requires some hacking to get round ASP.Net's assumption that you wouldn't try to do this. I favour a reusable approach which is explicit about the hackery involved.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebSandbox.Validators
{
/// <summary>
/// <para>
/// Validates a different validation group. Among the use cases envisioned are
/// <list type="">
/// <item>
/// Validating one set of rules when the user clicks "Save draft" and validating those rules plus some
/// extra consistency checks when they click "Send".
/// </item>
/// <item>
/// Grouping controls in a <code>fieldset</code> into a validation group with a
/// <code>ValidationSummary</code> and then having a final <code>ValidationSummary</code> which tells the
/// user which groups still have errors.
/// </item>
/// </list>
/// </para>
/// <para>
/// We include checks against setting <code>GroupToValidate</code> to the same value as
/// <code>ValidationGroup</code>, but we don't yet include checks for infinite recursion with one validator
/// in group A which validates group B and another in group B which validates group A. Caveat utilitor.
/// </para>
/// </summary>
public class ValidationGroupValidator : BaseValidator
{
public string GroupToValidate
{
get { return ViewState["G2V"] as string; }
set { ViewState["G2V"] = value; }
}
protected override bool ControlPropertiesValid()
{
if (string.IsNullOrEmpty(GroupToValidate)) throw new HttpException("GroupToValidate not specified");
if (GroupToValidate == ValidationGroup) throw new HttpException("Circular dependency");
// Don't call the base, because we don't want a "control to validate"
return true;
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("evaluationfunction", "ValidateValidationGroup");
writer.AddAttribute("GroupToValidate", GroupToValidate);
}
protected override void OnPreRender(EventArgs e)
{
// The standard validation JavaScript is too restrictive for this validator to work, so we have to replace a key function.
// Fortunately this runs later than the standard JS, so we can simply overwrite the existing value of Page_ClientValidate.
Page.ClientScript.RegisterStartupScript(typeof(ValidationGroupValidator), "validationJS", _ValidationJS);
base.OnPreRender(e);
}
protected override bool EvaluateIsValid()
{
if (string.IsNullOrEmpty(GroupToValidate)) return false;
bool groupValid = true;
foreach (IValidator validator in Page.GetValidators(GroupToValidate))
{
validator.Validate();
groupValid &= validator.IsValid;
}
return groupValid;
}
private const string _ValidationJS = #"<script type=""text/javascript"">
function ValidateValidationGroup(val) {
if (typeof(val.GroupToValidate) == ""string"") {
val.valid = PageMod_DoValidation(val.GroupToValidate);
}
}
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (!Page_Validators) return true;
var i, ctrl;
// Mark everything as valid.
for (i = 0; i < Page_Validators.length; i++) {
Page_Validators[i].finalValid = true;
}
if (Page_ValidationSummaries) {
for (i = 0; i < Page_ValidationSummaries.length; i++) {
Page_ValidationSummaries[i].finalDisplay = ""none"";
}
}
// Validate.
var groupValid = PageMod_DoValidation(validationGroup);
// Update displays once.
for (i = 0; i < Page_Validators.length; i++) {
ctrl = Page_Validators[i];
ctrl.isvalid = ctrl.finalValid;
ValidatorUpdateDisplay(ctrl);
}
if (Page_ValidationSummaries) {
for (i = 0; i < Page_ValidationSummaries.length; i++) {
ctrl = Page_ValidationSummaries[i];
ctrl.style.display = ctrl.finalDisplay;
}
}
ValidatorUpdateIsValid();
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
function PageMod_DoValidation(validationGroup) {
var groupValid = true, validator, i;
for (i = 0; i < Page_Validators.length; i++) {
validator = Page_Validators[i];
ValidatorValidate(validator, validationGroup, null);
validator.finalValid &= validator.isvalid;
groupValid &= validator.isvalid;
}
if (Page_ValidationSummaries) {
ValidationSummaryOnSubmit(validationGroup, groupValid);
var summary;
for (i = 0; i < Page_ValidationSummaries.length; i++) {
summary = Page_ValidationSummaries[i];
if (summary.style.display !== ""none"") summary.finalDisplay = summary.style.display;
}
}
return groupValid;
}
</script>";
}
}

Setting a WebControls TabIndex based on the ControlId of another control

I have an ASP.NET Webforms site that is regularly having features added.
The majority of time a new WebControl is added to the page and I need to increment the TabIndex to all subsequent controls on the page.
I'd prefer a more robust solution than choosing an arbitrary gap between the initial assigned tab indexes. Setting the tab indexes using the designer tab order functionality is one option but I'd prefer to stay in the source view.
Ideally, if I had, for example, three check boxes I'd like to be able to define the tabindex based off the previous controls tabindex. Then I'd only need to insert the new control and change one existing control.
For example, add a new property TabIndexAfterControlId to WebControl:
<asp:CheckBox ID="checkBoxA" runat="server" TabIndex="1"/>
<asp:CheckBox ID="checkBoxB" runat="server" TabIndexAfterControlId="checkBoxA"/>
<asp:CheckBox ID="checkBoxC" runat="server" TabIndexAfterControlId="checkBoxB"/>
My first thought was to extend System.Web.UI.WebControls.WebControl with a new property, but extension properties aren't supported.
Note: This approach worked for some webcontrols (DropDownLists) but not all of them (CheckBoxes). I've left it here for reference.
I've ended up with a solution that uses a code behind method to capture the relationship between controls.
<asp:CheckBox ID="checkBoxA" runat="server" TabIndex="1"/>
<asp:CheckBox ID="checkBoxB" runat="server" TabIndex='<%# TabIndexAfter(checkBoxB, checkBoxA) %>'/>
<asp:CheckBox ID="checkBoxC" runat="server" TabIndex='<%# TabIndexAfter(checkBoxC, checkBoxB) %>'/>
The code behind method will initially do a basic TabIndex assignment, which works well when the tab order follows the order of the controls on a page. Then during the PreRender event the tab index order will be checked again. This is important if the tab order doesn't not follow the natural flow of the page.
private LinkedList<WebControl> _webControlTabOrder;
/// <summary>
/// Assign the current WebControl TabIndex a value greater than the prior WebControl.
/// </summary>
/// <param name="currentWebControl">The current WebControl to set the TabIndex for</param>
/// <param name="priorWebControl">The prior WebControl to get the previous TabIndex from.</param>
/// <returns>The new TabIndex for the control</returns>
public int TabIndexAfter(WebControl currentWebControl, WebControl priorWebControl)
{
if (_webControlTabOrder == null)
{
_webControlTabOrder = new LinkedList<WebControl>();
this.PreRender += new EventHandler(UserControlBase_PreRender);
}
LinkedListNode<WebControl> priorNode = _webControlTabOrder.Find(currentWebControl);
if (priorNode == null)
{
priorNode = _webControlTabOrder.AddLast(priorWebControl);
}
_webControlTabOrder.AddAfter(priorNode, currentWebControl);
return priorWebControl.TabIndex + 1;
}
void UserControlBase_PreRender(object sender, EventArgs e)
{
LinkedListNode<WebControl> currentNode = _webControlTabOrder.First;
while(currentNode.Next != null)
{
LinkedListNode<WebControl> nextNode = currentNode.Next;
if (nextNode.Value.TabIndex <= currentNode.Value.TabIndex)
{
nextNode.Value.TabIndex = (short)(currentNode.Value.TabIndex + 1);
}
currentNode = nextNode;
}
}
My prior attempt using the data-binding syntax (<%# ... %>) to set the TabIndex for web controls failed when some controls wouldn't bind the TabIndex (CheckBox). It also wasn't ideal as I needed to pass a reference to the current control into the code behind method.
This time around I went with a custom ExpressionBuilder that accepts the name of the web control that the current control should follow in the tab order.
The TabIndexAfterExpressionBuilder initially returns the short -1 as the value. At the same time it registers with the LoadComplete event of the current Page. When this event fires both controls are found and the tab indexes set according to their relative positions.
Example WebControls using the TabIndex Expression Builder
<asp:TextBox ID="txtTextBox0" runat="server" TabIndex="1" /><br />
<asp:TextBox ID="txtTextBox1" runat="server" TabIndex="<%$ TabIndex:txtTextBox0 %>" /><br />
<asp:TextBox ID="txtTextBox2" runat="server" TabIndex="<%$ TabIndex:txtTextBox1 %>" />
TabIndexExpressionBuilder.cs
namespace ExpressionBuilders
{
public class TabIndexExpressionBuilder : ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
string priorControlId = entry.Expression.Trim();
string currentControlId = entry.ControlID;
CodeExpression[] inputParams = new CodeExpression[] { new CodePrimitiveExpression(priorControlId),
new CodePrimitiveExpression(currentControlId),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name) };
// Return a CodeMethodInvokeExpression that will invoke the GetRequestedValue method using the specified input parameters
return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()),
"GetRequestedValue",
inputParams);
}
public static object GetRequestedValue(string priorControlId, string currentControlId, Type targetType, string propertyName)
{
if (HttpContext.Current == null)
{
return null;
}
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
page.LoadComplete += delegate(object sender, EventArgs e)
{
WebControl currentWebControl = FindControlRecursive(page, currentControlId);
WebControl priorWebControl = FindControlRecursive(page, priorControlId);
if (currentWebControl != null && priorWebControl != null)
{
TabIndexAfter(page, currentWebControl, priorWebControl);
}
};
}
// Default TabIndex
short value = (short)-1;
return value;
}
private static WebControl FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) { return rootControl as WebControl; }
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null)
{
return controlToReturn as WebControl;
}
}
return null;
}
#region Tabbing
/// <summary>
/// Assign the current WebControl TabIndex a value greater than the prior WebControl.
/// </summary>
/// <param name="currentWebControl">The current Control to set the TabIndex for</param>
/// <param name="priorWebControl">The prior Control to get the previous TabIndex from.</param>
/// <returns>The new TabIndex for the current control</returns>
private static short TabIndexAfter(Page page, WebControl currentWebControl, object prior)
{
TabOrderWebControl tabOrderWebControl = page.FindControl("TabOrderWebControl") as TabOrderWebControl;
if (tabOrderWebControl == null)
{
tabOrderWebControl = new TabOrderWebControl();
page.Controls.Add(tabOrderWebControl);
}
WebControl priorWebControl = prior as WebControl;
if (priorWebControl == null)
{
string priorWebControlId = prior as string;
priorWebControl = page.FindControl(priorWebControlId) as WebControl;
}
if (currentWebControl == null) { throw new ArgumentNullException("currentWebControl"); }
if (priorWebControl == null) { throw new ArgumentNullException("priorWebControl"); }
if (currentWebControl == priorWebControl) { throw new ArgumentException("priorWebControl is the same as the currentWebControl", "priorWebControl"); }
tabOrderWebControl.TabIndexAfter(currentWebControl, priorWebControl);
return currentWebControl.TabIndex;
}
#endregion
}
}
TabOrderWebControl.cs
namespace ExpressionBuilders
{
public class TabOrderWebControl :
WebControl
{
LinkedList<WebControl> _webControlTabOrder;
internal void TabIndexAfter(System.Web.UI.WebControls.WebControl currentWebControl, System.Web.UI.WebControls.WebControl priorWebControl)
{
if (_webControlTabOrder == null)
{
_webControlTabOrder = new LinkedList<WebControl>();
this.Page.PreRender += new EventHandler(PageBase_PreRender);
}
LinkedListNode<WebControl> priorNode = _webControlTabOrder.Find(priorWebControl);
LinkedListNode<WebControl> currentNode = _webControlTabOrder.Find(currentWebControl);
if (currentNode != null)
{
//The current node is already in the list (it must preceed some other control)
//Add the prior node before it.
if (priorNode == null)
{
priorNode = _webControlTabOrder.AddBefore(currentNode, priorWebControl);
}
else
{
//Both nodes are already in the list. Ensure the ordering is correct.
bool foundPriorNode = false;
foreach (WebControl controlNode in _webControlTabOrder)
{
if (controlNode == priorWebControl)
{
foundPriorNode = true;
}
else if (controlNode == currentWebControl)
{
if (foundPriorNode)
{
//Ordering is correct
break;
}
else
{
throw new ApplicationException(string.Format("WebControl ordering is incorrect. Found {1} before {0}", currentWebControl.ID, priorWebControl.ID));
}
}
}
}
}
else if (priorNode == null)
{
//Neither control is in the list yet.
priorNode = _webControlTabOrder.AddLast(priorWebControl);
currentNode = _webControlTabOrder.AddAfter(priorNode, currentWebControl);
}
else
{
//Prior node is already in the list but the current node isn't
currentNode = _webControlTabOrder.AddAfter(priorNode, currentWebControl);
}
}
/// <summary>
/// Once all the controls have been added to the linked list ensure the tab ordering is correct.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void PageBase_PreRender(object sender, EventArgs e)
{
AssignTabIndexes();
}
/// <summary>
/// Reassign tab indexes for all known controls.
/// </summary>
protected void AssignTabIndexes()
{
LinkedListNode<WebControl> currentNode = _webControlTabOrder.First;
while (currentNode.Next != null)
{
LinkedListNode<WebControl> nextNode = currentNode.Next;
WebControl currentControl = currentNode.Value;
WebControl nextControl = nextNode.Value;
if (currentControl == nextControl)
{
throw new ApplicationException("Control added twice");
}
short currentTabIndex = currentControl.TabIndex;
short nextTabIndex = nextControl.TabIndex;
if (nextTabIndex <= currentTabIndex)
{
nextControl.TabIndex = (short)(currentTabIndex + 1);
}
currentNode = nextNode;
}
}
}
}
web.config
<system.web>
<compilation debug="true" targetFramework="4.0">
<expressionBuilders>
<add expressionPrefix="TabIndex" type="ExpressionBuilders.TabIndexExpressionBuilder, ExpressionBuilders"/>
</expressionBuilders>
</compilation>
</system.web>

How to decode viewstate

I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found Fridz Onion's ViewState Decoder but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy & paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate?
Here's an online ViewState decoder:
http://ignatu.co.uk/ViewStateDecoder.aspx
Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):
http://viewstatedecoder.azurewebsites.net/
Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.
Here is the source code for a ViewState visualizer from Scott Mitchell's article on ViewState (25 pages)
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.UI;
namespace ViewStateArticle.ExtendedPageClasses
{
/// <summary>
/// Parses the view state, constructing a viaully-accessible object graph.
/// </summary>
public class ViewStateParser
{
// private member variables
private TextWriter tw;
private string indentString = " ";
#region Constructor
/// <summary>
/// Creates a new ViewStateParser instance, specifying the TextWriter to emit the output to.
/// </summary>
public ViewStateParser(TextWriter writer)
{
tw = writer;
}
#endregion
#region Methods
#region ParseViewStateGraph Methods
/// <summary>
/// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
/// </summary>
/// <param name="viewState">The view state object to start parsing at.</param>
public virtual void ParseViewStateGraph(object viewState)
{
ParseViewStateGraph(viewState, 0, string.Empty);
}
/// <summary>
/// Emits a readable version of the view state to the TextWriter passed into the object's constructor.
/// </summary>
/// <param name="viewStateAsString">A base-64 encoded representation of the view state to parse.</param>
public virtual void ParseViewStateGraph(string viewStateAsString)
{
// First, deserialize the string into a Triplet
LosFormatter los = new LosFormatter();
object viewState = los.Deserialize(viewStateAsString);
ParseViewStateGraph(viewState, 0, string.Empty);
}
/// <summary>
/// Recursively parses the view state.
/// </summary>
/// <param name="node">The current view state node.</param>
/// <param name="depth">The "depth" of the view state tree.</param>
/// <param name="label">A label to display in the emitted output next to the current node.</param>
protected virtual void ParseViewStateGraph(object node, int depth, string label)
{
tw.Write(System.Environment.NewLine);
if (node == null)
{
tw.Write(String.Concat(Indent(depth), label, "NODE IS NULL"));
}
else if (node is Triplet)
{
tw.Write(String.Concat(Indent(depth), label, "TRIPLET"));
ParseViewStateGraph(((Triplet) node).First, depth+1, "First: ");
ParseViewStateGraph(((Triplet) node).Second, depth+1, "Second: ");
ParseViewStateGraph(((Triplet) node).Third, depth+1, "Third: ");
}
else if (node is Pair)
{
tw.Write(String.Concat(Indent(depth), label, "PAIR"));
ParseViewStateGraph(((Pair) node).First, depth+1, "First: ");
ParseViewStateGraph(((Pair) node).Second, depth+1, "Second: ");
}
else if (node is ArrayList)
{
tw.Write(String.Concat(Indent(depth), label, "ARRAYLIST"));
// display array values
for (int i = 0; i < ((ArrayList) node).Count; i++)
ParseViewStateGraph(((ArrayList) node)[i], depth+1, String.Format("({0}) ", i));
}
else if (node.GetType().IsArray)
{
tw.Write(String.Concat(Indent(depth), label, "ARRAY "));
tw.Write(String.Concat("(", node.GetType().ToString(), ")"));
IEnumerator e = ((Array) node).GetEnumerator();
int count = 0;
while (e.MoveNext())
ParseViewStateGraph(e.Current, depth+1, String.Format("({0}) ", count++));
}
else if (node.GetType().IsPrimitive || node is string)
{
tw.Write(String.Concat(Indent(depth), label));
tw.Write(node.ToString() + " (" + node.GetType().ToString() + ")");
}
else
{
tw.Write(String.Concat(Indent(depth), label, "OTHER - "));
tw.Write(node.GetType().ToString());
}
}
#endregion
/// <summary>
/// Returns a string containing the <see cref="IndentString"/> property value a specified number of times.
/// </summary>
/// <param name="depth">The number of times to repeat the <see cref="IndentString"/> property.</param>
/// <returns>A string containing the <see cref="IndentString"/> property value a specified number of times.</returns>
protected virtual string Indent(int depth)
{
StringBuilder sb = new StringBuilder(IndentString.Length * depth);
for (int i = 0; i < depth; i++)
sb.Append(IndentString);
return sb.ToString();
}
#endregion
#region Properties
/// <summary>
/// Specifies the indentation to use for each level when displaying the object graph.
/// </summary>
/// <value>A string value; the default is three blank spaces.</value>
public string IndentString
{
get
{
return indentString;
}
set
{
indentString = value;
}
}
#endregion
}
}
And here's a simple page to read the viewstate from a textbox and graph it using the above code
private void btnParse_Click(object sender, System.EventArgs e)
{
// parse the viewState
StringWriter writer = new StringWriter();
ViewStateParser p = new ViewStateParser(writer);
p.ParseViewStateGraph(txtViewState.Text);
ltlViewState.Text = writer.ToString();
}
As another person just mentioned, it's a base64 encoded string. In the past, I've used this website to decode it:
http://www.motobit.com/util/base64-decoder-encoder.asp
JavaScript-ViewState-Parser:
http://mutantzombie.github.com/JavaScript-ViewState-Parser/
https://github.com/mutantzombie/JavaScript-ViewState-Parser/
The parser should work with most non-encrypted ViewStates. It doesn’t
handle the serialization format used by .NET version 1 because that
version is sorely outdated and therefore too unlikely to be
encountered in any real situation.
http://deadliestwebattacks.com/2011/05/29/javascript-viewstate-parser/
Parsing .NET ViewState
A Spirited Peek into ViewState, Part I:
http://deadliestwebattacks.com/2011/05/13/a-spirited-peek-into-viewstate-part-i/
A Spirited Peek into ViewState, Part II:
http://deadliestwebattacks.com/2011/05/25/a-spirited-peek-into-viewstate-part-ii/
Here's another decoder that works well as of 2014: http://viewstatedecoder.azurewebsites.net/
This worked on an input on which the Ignatu decoder failed with "The serialized data is invalid" (although it leaves the BinaryFormatter-serialized data undecoded, showing only its length).
This is somewhat "native" .NET way of converting ViewState from string into StateBag
Code is below:
public static StateBag LoadViewState(string viewState)
{
System.Web.UI.Page converterPage = new System.Web.UI.Page();
HiddenFieldPageStatePersister persister = new HiddenFieldPageStatePersister(new Page());
Type utilClass = typeof(System.Web.UI.BaseParser).Assembly.GetType("System.Web.UI.Util");
if (utilClass != null && persister != null)
{
MethodInfo method = utilClass.GetMethod("DeserializeWithAssert", BindingFlags.NonPublic | BindingFlags.Static);
if (method != null)
{
PropertyInfo formatterProperty = persister.GetType().GetProperty("StateFormatter", BindingFlags.NonPublic | BindingFlags.Instance);
if (formatterProperty != null)
{
IStateFormatter formatter = (IStateFormatter)formatterProperty.GetValue(persister, null);
if (formatter != null)
{
FieldInfo pageField = formatter.GetType().GetField("_page", BindingFlags.NonPublic | BindingFlags.Instance);
if (pageField != null)
{
pageField.SetValue(formatter, null);
try
{
Pair pair = (Pair)method.Invoke(null, new object[] { formatter, viewState });
if (pair != null)
{
MethodInfo loadViewState = converterPage.GetType().GetMethod("LoadViewStateRecursive", BindingFlags.Instance | BindingFlags.NonPublic);
if (loadViewState != null)
{
FieldInfo postback = converterPage.GetType().GetField("_isCrossPagePostBack", BindingFlags.NonPublic | BindingFlags.Instance);
if (postback != null)
{
postback.SetValue(converterPage, true);
}
FieldInfo namevalue = converterPage.GetType().GetField("_requestValueCollection", BindingFlags.NonPublic | BindingFlags.Instance);
if (namevalue != null)
{
namevalue.SetValue(converterPage, new NameValueCollection());
}
loadViewState.Invoke(converterPage, new object[] { ((Pair)((Pair)pair.First).Second) });
FieldInfo viewStateField = typeof(Control).GetField("_viewState", BindingFlags.NonPublic | BindingFlags.Instance);
if (viewStateField != null)
{
return (StateBag)viewStateField.GetValue(converterPage);
}
}
}
}
catch (Exception ex)
{
if (ex != null)
{
}
}
}
}
}
}
}
return null;
}
You can ignore the URL field and simply paste the viewstate into the Viewstate string box.
It does look like you have an old version; the serialisation methods changed in ASP.NET 2.0, so grab the 2.0 version
Best way in python is use this link.
A small Python 3.5+ library for decoding ASP.NET viewstate.
First install that: pip install viewstate
>>> from viewstate import ViewState
>>> base64_encoded_viewstate = '/wEPBQVhYmNkZQ9nAgE='
>>> vs = ViewState(base64_encoded_viewstate)
>>> vs.decode()
('abcde', (True, 1))
Online Viewstate Viewer made by Lachlan Keown:
http://lachlankeown.blogspot.com/2008/05/online-viewstate-viewer-decoder.html
Normally, ViewState should be decryptable if you have the machine-key, right? After all, ASP.net needs to decrypt it, and that is certainly not a black box.

Resources