How to execute multiple ClientScript.RegisterStartupScript in ASP.NET c#?

痴心易碎 提交于 2019-12-13 00:48:27

问题


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


回答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




回答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.




回答3:


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.




回答4:


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);



回答5:


I usually use this method to show alert and I can call it whenever I need.

public class BasePage : System.Web.UI.Page {
        public void ShowNotif(string sMessage) {
            ScriptManager.RegisterStartupScript(Page, GetType(), Guid.NewGuid().ToString(), "alert('" + sMessage.Replace("'", "\'") + "'); ", true);
        }
}

It means I can run Javascript code multiple times.

Usage : Every Webform Class, extend BasePage like this :

public partial class FinanceHostToHost : BasePage{ //Not extend System.Web.UI.Page
....
}

Function call :

            ShowNotif("Hello");
            ShowNotif("World");
            ShowNotif("Any message");
            ShowNotif("Message again");


来源:https://stackoverflow.com/questions/12534417/how-to-execute-multiple-clientscript-registerstartupscript-in-asp-net-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!