verificar sitio site pagina google como c# asp.net page-lifecycle

c# - sitio - En la devolución de datos, ¿cómo puedo verificar qué control causa la devolución de datos en el evento Page_Init?



google-site-verification (8)

En la devolución de datos, ¿cómo puedo verificar qué control causa la devolución de datos en el evento Page_Init?

protected void Page_Init(object sender, EventArgs e) { //need to check here which control cause postback? }

Gracias


Además de las respuestas anteriores, para usar Request.Params["__EVENTTARGET"] debe establecer la opción:

buttonName.UseSubmitBehavior = false;


Aquí hay un código que podría hacer el truco para ti (tomado del blog de Ryan Farley )

public static Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname != null && ctrlname != string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; }


Asumiendo que es un control de servidor, puede usar Request["ButtonName"]

Para ver si se hizo clic en un botón específico: if (Request["ButtonName"] != null)


Para obtener el nombre exacto de control, use:

string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;


Si necesita verificar qué control causó la devolución de datos, entonces simplemente podría comparar directamente ["__EVENTTARGET"] con el control que le interesa:

if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"]) { /*do special stuff*/ }

Esto supone que, de todos modos, comparará el resultado de cualquier método de extensión GetPostBackControl(...) . Puede que no maneje CADA situación, pero si funciona es más simple. Además, no buscará en la página buscando un control que no le interese para comenzar.


Veo que ya hay algunos buenos consejos y métodos que sugieren cómo recuperar el control de la publicación. Sin embargo, encontré otra página web ( blog de Mahesh ) con un método para recuperar el ID de control de devolución posterior.

Lo publicaré aquí con una pequeña modificación, incluida la posibilidad de hacer una clase de extensión. Con suerte, es más útil de esa manera.

/// <summary> /// Gets the ID of the post back control. /// /// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx /// </summary> /// <param name = "page">The page.</param> /// <returns></returns> public static string GetPostBackControlId(this Page page) { if (!page.IsPostBack) return string.Empty; Control control = null; // first we will check the "__EVENTTARGET" because if post back made by the controls // which used "_doPostBack" function also available in Request.Form collection. string controlName = page.Request.Params["__EVENTTARGET"]; if (!String.IsNullOrEmpty(controlName)) { control = page.FindControl(controlName); } else { // if __EVENTTARGET is null, the control is a button type and we need to // iterate over the form collection to find it // ReSharper disable TooWideLocalVariableScope string controlId; Control foundControl; // ReSharper restore TooWideLocalVariableScope foreach (string ctl in page.Request.Form) { // handle ImageButton they having an additional "quasi-property" // in their Id which identifies mouse x and y coordinates if (ctl.EndsWith(".x") || ctl.EndsWith(".y")) { controlId = ctl.Substring(0, ctl.Length - 2); foundControl = page.FindControl(controlId); } else { foundControl = page.FindControl(ctl); } if (!(foundControl is IButtonControl)) continue; control = foundControl; break; } } return control == null ? String.Empty : control.ID; }

Actualización (22-07-2016): la comprobación de tipo para Button y ImageButton cambió para buscar IButtonControl para permitir que se IButtonControl las devoluciones de controles de terceros.


Ya sea directamente en los parámetros de formulario o

string controlName = this.Request.Params.Get("__EVENTTARGET");

Editar : Para verificar si un control causó una devolución de datos (manualmente):

// input Image with name="imageName" if (this.Request["imageName"+".x"] != null) ...;//caused postBack // Other input with name="name" if (this.Request["name"] != null) ...;//caused postBack

También podría recorrer todos los controles y verificar si alguno de ellos causó un posback usando el código anterior.


if (Request.Params["__EVENTTARGET"] != null) { if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID")) { DoWhateverYouWant(); } }