How to execute multiple ClientScript.RegisterStartupScript in ASP.NET c#?
Solution 1
A little extra information information would be helpful. You aren't limited from using RegisterStatupScript more than once, but you are limited from registering the same type/key combination more than once (this is a feature, not a limitation).
If you need to register different scripts, use a unique key. If you are simply doing a postback, re-registering the startup script will/should work.
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx
Solution 2
ClientScript.RegisterStartupScript(this.GetType(),
"myFileOpenScript",
"<script>window.open('/Archivos/" + strArchivo + "');</script>");
The script key here is myFileOpenScript
.
A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script. http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
You can use Guid.NewGuid()
to generate a different key each time. And you would probably want to use
RegisterStartupScript(Type, String, String, Boolean)
instead. The last parameter (boolean) tells it to create the script
tags for you, so the script parameter can contain only your code not worrying about the tags.
Solution 3
Since Jamie Tores answer lacks an example
This is correct
ScriptManager.RegisterStartupScript(Page, GetType(), "setDatePickerStartDate", "javascript:setDatePickerStartDate('" + s_capstoneStartDate + "'); ", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "setDatePickerEndDate", "javascript:setDatePickerEndDate('" + s_capstoneEndDate + "'); ", true);
This is wrong since the 3rd parameter is the same in both
ScriptManager.RegisterStartupScript(Page, GetType(), "Javascript", "javascript:setDatePickerStartDate('" + s_StartDate + "'); ", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "Javascript", "javascript:setDatePickerEndDate('" + s_EndDate + "'); ", true);
Solution 4
You're right to avoid using Response.Write
in an event handler like that: it executes before the Render
phase of the page lifecycle, and therefore outputs at the top of the HTML page.
You could use a StringBuilder
to build the script in the foreach DataRow
loop, then register it once.
Solution 5
I know that I'm a bit late to the party, but I needed to accomplish the same thing. With the knowledge that @JaimeTorres provided that there has to be a unique key, I just made a static method where you pass in the Page and the Message, and the method creates an arbritrary "key" with a basic Do....While loop and keeps checking the keys until we find the first one that hasn't been used yet. Then it uses that to display the message. Works just fine for my purposes, maybe someone else can make use of it if they find this answer!
/// <summary>
/// Shows a basic MessageBox on the passed in page
/// </summary>
/// <param name="page">The Page object to show the message on</param>
/// <param name="message">The message to show</param>
/// <returns></returns>
public static ShowMessageBox(Page page, string message)
{
Type cstype = page.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = page.ClientScript;
// Find the first unregistered script number
int ScriptNumber = 0;
bool ScriptRegistered = false;
do
{
ScriptNumber++;
ScriptRegistered = cs.IsStartupScriptRegistered(cstype, "PopupScript" + ScriptNumber);
} while (ScriptRegistered == true);
//Execute the new script number that we found
cs.RegisterStartupScript(cstype, "PopupScript" + ScriptNumber, "alert('" + message + "');", true);
}
Victor
Updated on June 28, 2022Comments
-
Victor almost 2 years
I'm developing a gridview in which you can download multiple files with one button.
Here's my gridview:
<asp:GridView ID="grdvHistorialMensajes" runat="server" AllowPaging="True" AutoGenerateColumns="False" CellPadding="4" AllowSorting="true" EmptyDataText="No Hay Mensajes Enviados" ForeColor="#333333" GridLines="None" CellSpacing="1" onpageindexchanging="grdvHistorialMensajes_PageIndexChanging" onrowcommand="grdvHistorialMensajes_RowCommand" onsorting="grdvHistorialMensajes_Sorting"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <Columns> <asp:BoundField DataField="CorreoCliente" HeaderText="Correo Del Cliente" SortExpression="CorreoCliente" /> <asp:BoundField DataField="CorreosAdicionales" HeaderText="Correos Adicionales" SortExpression="CorreosAdicionales" /> <asp:BoundField DataField="Tema" HeaderText="Tema" SortExpression="Tema" /> <asp:BoundField DataField="Mensaje" HeaderText="Mensaje" SortExpression="Mensaje" /> <asp:TemplateField HeaderText="Fecha" SortExpression="Fecha"> <ItemTemplate> <%# DataBinder.Eval(Container.DataItem, "Fecha", "{0:dd/MM/yyyy}")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="tbxFecha" runat="server" Text='<%#Bind("Fecha","{0:dd/MM/yyyy}") %>' ValidationGroup="gpEdicionAgenda"> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Hora" HeaderText="Hora" SortExpression="Hora" /> <asp:BoundField DataField="Archivos" HeaderText="Archivos" SortExpression="Archivos" /> <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="imgBtnDescargarArchivos" runat="server" CommandArgument='<%# Eval("IdMensaje")%>' CommandName="Descargar" Height="16px" ImageUrl="~/img/activar.png" ToolTip="Descargar" Width="16px" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="imgBtnVerMas" runat="server" CommandArgument='<%# Eval("IdMensaje")%>' CommandName="VerMas" Height="16px" ImageUrl="~/img/search.png" ToolTip="Ver Mas" Width="16px" /> </ItemTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> </asp:GridView>
Whenever I click on the "Descargar" RowCommand, I originally used this:
if (e.CommandName == "Descargar") { DataTable dt = ConexionBD.GetInstanciaConexionBD().GetArchivosPorMensaje(Convert.ToInt32(e.CommandArgument)); foreach (DataRow dr in dt.Rows) { string strArchivo = dr["Nombre"].ToString(); string strExtension = Path.GetExtension(strArchivo).ToLower(); Response.Write("<script>window.open('/Archivos/" + strArchivo + "');</script>"); } }
When I clicked, if that row had let's say 1 pdf, 1 jpg and 1 doc, it opened both the pdf and the jpg in a different window and the doc would be downloaded. That's exactly what I want. However, I noticed that whenever a new page is opened (in the case of the pdf and jpg) all the font in the page is altered. So I wanted to find a solution and then I tried this:
if (e.CommandName == "Descargar") { DataTable dt = ConexionBD.GetInstanciaConexionBD().GetArchivosPorMensaje(Convert.ToInt32(e.CommandArgument)); foreach (DataRow dr in dt.Rows) { string strArchivo = dr["Nombre"].ToString(); string strExtension = Path.GetExtension(strArchivo).ToLower(); ClientScript.RegisterStartupScript(this.GetType(), "myFileOpenScript", "<script>window.open('/Archivos/" + strArchivo + "');</script>"); } }
When I open a pdf file, the font is not altered this time, however, It would only open/download the first file that appears int dt.Rows[0] (dt.Rows[1] on won't open). I suppose that a Response.Write can be deployed multiple times, however, a ClientScript.RegisterStartupScript probably can only be executed once.
Is there another method I can use to not alter the page's letter font and to open multiple files with a single click?
Or how could I execute ClientScript.RegisterStartupScript multiple times??
Thanks In Advance
-
Chris B about 11 yearsIn case it helps anyone - when using multiple RegisterStartupScripts, be sure to terminate the javascript with a semicolon. I spent an hour tearing out my hear wondering why unique type/key combinations weren't working. The missing semicolons only became apparent when I added a second startup tag.