Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
sp:aspnet:wapps [2009/08/19 09:02] alfred |
sp:aspnet:wapps [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 92: | Línea 92: | ||
| ==== XmlDataSource ==== | ==== XmlDataSource ==== | ||
| + | |||
| Línea 136: | Línea 137: | ||
| <code xml> | <code xml> | ||
| <%# DataBinder.Eval(Container.DataItem, "field_name") %> | <%# DataBinder.Eval(Container.DataItem, "field_name") %> | ||
| + | </code> | ||
| + | El cual también puede ser usuado como (El método ''getEstatName'' devuelve un ''string''): | ||
| + | <code xml> | ||
| + | <%# codegest.app_incidencies.incidencies.getEstatName(((ATMDB.ATM_INCIDENCIES_HISTORIC)Container.DataItem).estat) %> | ||
| </code> | </code> | ||
| Línea 247: | Línea 252: | ||
| </asp:GridView> | </asp:GridView> | ||
| </code> | </code> | ||
| + | |||
| + | |||
| Línea 254: | Línea 261: | ||
| ==== Como: GridView ==== | ==== Como: GridView ==== | ||
| + | === Coger el identificador de una fila en un campo no visible === | ||
| + | Para ello deberemos utilizar la pripiedad ''DataKeyNames'' del GridView para indicar los campos clave: | ||
| + | <code xml> | ||
| + | <asp:GridView DataKeyNames="ID" ID="GridView1″ ... | ||
| + | </code> | ||
| + | Luego, de los campos definidos como ''Visible="false"'' podremos recoger su id mediante: | ||
| + | * Por el nombre: | ||
| + | <code csharp> | ||
| + | int id = GridView1.DataKeys["ID"].Value; | ||
| + | </code> | ||
| + | * Por el índice: | ||
| + | <code csharp> | ||
| + | int id = GridView1.DataKeys[0].Value; | ||
| + | </code> | ||
| + | * O al utilizar ''RowUdating'' o ''RowDataBound'': | ||
| + | <code csharp> | ||
| + | int id = GridView1.DataKeys[e.RowIndex].Value; | ||
| + | </code> | ||
| === Llenar un GridView con objetos de tipo anónimo === | === Llenar un GridView con objetos de tipo anónimo === | ||
| Es decir, teniendo un código del estilo: | Es decir, teniendo un código del estilo: | ||
| Línea 303: | Línea 328: | ||
| * **Alinear horizontalmente una columna**: ''this.grid.Columns[3].ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;'' | * **Alinear horizontalmente una columna**: ''this.grid.Columns[3].ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;'' | ||
| * **Hacer que aparezcan las tags ''THEAD'' y ''TBODY''**: ''this.GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;'' | * **Hacer que aparezcan las tags ''THEAD'' y ''TBODY''**: ''this.GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;'' | ||
| + | * **Formatear una fecha**: ''<asp:boundfield datafield="Your_Date_Column" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />'' | ||
| ==== Repeater ==== | ==== Repeater ==== | ||
| Línea 349: | Línea 375: | ||
| + | Si quisieramos recoger los datos que se han mostrado en un control repeater podremos acceder a su colección de Items: | ||
| + | <code csharp> | ||
| + | foreach (var item in this.Repeater1.Items) | ||
| + | { | ||
| + | AtmUsers.AtmUserAppConf conf = (AtmUsers.AtmUserAppConf)((RepeaterItem)item).DataItem; | ||
| + | DropDownList lPags = (DropDownList)((RepeaterItem)item).FindControl("pagList"); | ||
| + | HiddenField id = (HiddenField)((RepeaterItem)item).FindControl("idPag"); | ||
| + | } | ||
| + | </code> | ||
| ===== Controles ===== | ===== Controles ===== | ||
| Línea 378: | Línea 413: | ||
| ... | ... | ||
| </code> | </code> | ||
| + | |||
| Línea 391: | Línea 427: | ||
| + | ==== Controles Web de usuario ==== | ||
| + | Un Web User Control es un control que crea el programador y que se puede reutilzar en las páginas asp.net, son clases que heredan de ''System.Web.UI.UserControl'' que a su vez hereda de ''System.Web.UI.TemplateParser'' y se guardan en archivos .ascx. \\ | ||
| + | Para utilizar el control en nuestro formulario web de usuario primero tendremos que registrarlo a partir de la tag ''Register''. La propiedad ''TagPrefix'' de esta indica un espacio de nombres único para el control dentro del .aspx, la ''TagName'' es el nombre por el cual nos referiremos a él y la ''Src'' es la página donde se encuentre el fichero. | ||
| + | <code> | ||
| + | <%@ Register TagPrefix="Acme" TagName="Message" Src="pagelet1.ascx" %> | ||
| + | </code> | ||
| + | Luego podremos utilizar el control haciendo: ''<namespace:nombre_control runat="server" />'': | ||
| + | <code> | ||
| + | <Acme:Message runat="server" /> | ||
| + | </code> | ||
| + | Al igual que los web forms los user controls pueden contener code-behind. Si en este ponemos propiedades públicas podremos acceder a ellas a partir de las tags en el .aspx: \\ | ||
| + | Código en el .ascx: | ||
| + | <code> | ||
| + | <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication7.WebUserControl1" %> | ||
| + | <asp:Label ID="lbl" runat="server"></asp:Label> | ||
| + | </code> | ||
| + | Código en el .ascx.cs: | ||
| + | <code csharp> | ||
| + | public partial class WebUserControl1 : System.Web.UI.UserControl | ||
| + | { | ||
| + | public String texto = ""; | ||
| + | public String Text | ||
| + | { | ||
| + | set | ||
| + | { | ||
| + | this.text = value; | ||
| + | } | ||
| + | get | ||
| + | { | ||
| + | return this.text; | ||
| + | } | ||
| + | } | ||
| + | protected void Page_Load(object sender, EventArgs e) | ||
| + | { | ||
| + | this.lbl.Text = this.texto; | ||
| + | } | ||
| + | } | ||
| + | </code> | ||
| + | Código en el .aspx: | ||
| + | <code> | ||
| + | ... | ||
| + | %@ Register TagPrefix="ctrl" TagName="webcontrol" Src="WebUserControl1.ascx" %> | ||
| + | ... | ||
| + | <ctrl:webcontrol runat="server" texto="hasodfasdf" /> | ||
| + | ... | ||
| + | </code> | ||
| + | Luego también podremos agregarlo a partir del código: | ||
| + | <code csharp> | ||
| + | Control c1 = LoadControl("userctrl7.ascx"); | ||
| + | ((UserCtrl7)c1).Category = "business"; | ||
| + | Page.Controls.Add(c1); | ||
| + | </code> | ||
| + | El tipo | ||
| + | El nombre de la clase generada por el control lo podemos definir a partir de la propiedad ClassName de la tag Control: | ||
| + | <code> | ||
| + | <%@ Control ClassName="UserCtrl7" %> | ||
| + | </code> | ||
| ===== Como... ===== | ===== Como... ===== | ||
| - | **Crear url relativa correctamente**: | + | |
| + | ==== Pequeños 'howto' ==== | ||
| + | **Construir una url relativa**: | ||
| <code xml> | <code xml> | ||
| <script type="text/javascript" src="<%= ResolveClientUrl("~/jscripts/libs/jquery.js") %>"></script> | <script type="text/javascript" src="<%= ResolveClientUrl("~/jscripts/libs/jquery.js") %>"></script> | ||
| + | </code> | ||
| + | |||
| + | ==== Descarga dinámica de ficheros ==== | ||
| + | :!: Podemos crear un fichero a tiempo real y hacer que el usuario lo reciba: | ||
| + | <code csharp> | ||
| + | Response.Clear(); | ||
| + | Response.Buffer = true; | ||
| + | Response.AddHeader("content-disposition", "attachment;filename=" + nameFile + ".xls"); | ||
| + | Response.Charset = ""; | ||
| + | Response.ContentType = "application/vnd.ms-excel"; | ||
| + | StringWriter sw = new StringWriter(); | ||
| + | HtmlTextWriter hw = new HtmlTextWriter(sw); | ||
| + | gv.RenderControl(hw); | ||
| + | string style = @"<style> .textmode { mso-number-format:\@; } </style>"; | ||
| + | Response.Write(style); | ||
| + | Response.Output.Write(sw.ToString()); | ||
| + | Response.Flush(); | ||
| + | Response.End(); | ||
| + | </code> | ||
| + | |||
| + | <code csharp> | ||
| + | Response.Clear(); | ||
| + | Response.ContentType = "application/vnd.ms-excel"; | ||
| + | Response.WriteFile("c:\\a.xls"); | ||
| + | Response.Flush(); | ||
| + | File.Delete("c:\\a.xls"); | ||
| + | Response.End(); | ||
| + | </code> | ||
| + | |||
| + | Ejemplos de cabeceras: | ||
| + | <code> | ||
| + | Response.ContentType = "application/vnd.ms-excel"; | ||
| + | Response.AddHeader("Content-Length", file.Length.ToString()); | ||
| + | Response.AddHeader("Content-Disposition", "inline;filename=temp.txt"); | ||
| + | Response.AddHeader("content-disposition", "attachment;filename=" + nameFile + ".xls"); | ||
| </code> | </code> | ||
| Línea 525: | Línea 654: | ||
| this.clickmeupdate.InnerText = "Se ha hecho PostBack"; | this.clickmeupdate.InnerText = "Se ha hecho PostBack"; | ||
| </code> | </code> | ||
| + | |||
| Línea 535: | Línea 665: | ||
| </code> | </code> | ||
| + | ===== Otros ===== | ||
| + | |||
| + | |||
| + | |||
| + | ==== Code Snippets ==== | ||
| + | === LinkButton de eliminar con confirmación en cliente === | ||
| + | <code xml> | ||
| + | <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="DeleteItem" | ||
| + | Text="Delete" OnClientClick="return confirm(’Are you sure you want to\ndelete this item?’);"> | ||
| + | </asp:LinkButton> | ||
| + | </code> | ||
| + | |||
| + | === Clase HttpHandler que devuelva una imágen dinámicamente === | ||
| + | <code csharp> | ||
| + | public class Handler1 : IHttpHandler { | ||
| + | public void ProcessRequest(HttpContext context) { | ||
| + | context.Response.ContentType = "image/jpeg"; | ||
| + | System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100); | ||
| + | System.Drawing.Brush b = new System.Drawing.SolidBrush (System.Drawing.Color.FromArgb(255, 0,0)); | ||
| + | System.Drawing.Graphics.FromImage(bmp).FillRectangle(b, new System.Drawing.Rectangle(0, 0, 100, 100)); | ||
| + | bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); | ||
| + | } | ||
| + | |||
| + | public bool IsReusable { | ||
| + | get { | ||
| + | return false; | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | </code> | ||
| + | Aunque también lo podrías poner en una página: | ||
| + | <code> | ||
| + | <%@ Page ContentType = "image/jpeg"%> | ||
| + | <%@ Import Namespace = "System.Drawing" %> | ||
| + | <%@ Import Namespace = "System.Drawing.Imaging" %> | ||
| + | |||
| + | <Script Runat = "Server"> | ||
| + | Bitmap bmp = new Bitmap(100, 100); | ||
| + | Brush b = new SolidBrush (System.Drawing.Color.FromArgb(255, 0,0)); | ||
| + | Graphics.FromImage(bmp).FillRectangle(b, new Rectangle(0, 0, 100, 100)); | ||
| + | bmp.Save(Response.OutputStream, ImageFormat.Jpeg); | ||
| + | </Script> | ||
| + | </code> | ||
| + | |||
| + | ==== Notas ==== | ||
| + | * Si un formulario retorna tags xml ASP.NET se quejará por inseguridad, para evitarle agregaremos en la directiva ''Page'' inicial del aspx: ''ValidateRequest="false"''. | ||
| + | * Para no liarse con los estados de página de ASP.NET y con los LinqSources y los ''DetailsView'' puedes intentar trabajar como si dichos estados no existiesen, es decir, utilizar el código necesario en los eventos ''OnInserting'', ''OnInserted'', ''OnUpdating''... Olvidarse de si es //callback//, y mediante los ''Response.Redirect'' indicar en la QueryString si se llama a la página para editar, insertar... Y configurar el ''DetailsView'' mediante el método ''ChangeMode'' en la sobreescritura del método ''OnPreRender''. | ||
| + | * Si queremos forzar a un ''GridView'' (o ''Repeater'') para que se muestre sin que este tenga resultados le asignaremos una ''DataTable'' vacía: | ||
| + | <code csharp> | ||
| + | System.Data.DataTable table = new System.Data.DataTable(); | ||
| + | table.Rows.Add(table.NewRow()); | ||
| + | this.Repeater1.DataSource = table; | ||
| + | this.Repeater1.DataBind(); | ||
| + | </code> | ||