如何在ASP.NET c#中执行多个ClientScript.RegisterStartupScript?

如何在ASP.NET c#中执行多个ClientScript.RegisterStartupScript?,c#,asp.net,response.write,registerstartupscript,clientscript,C#,Asp.net,Response.write,Registerstartupscript,Clientscript,我正在开发一个gridview,您可以通过一个按钮下载多个文件 以下是我的gridview: <asp:GridView ID="grdvHistorialMensajes" runat="server" AllowPaging="True" AutoGenerateColumns="False" CellPadding="4" AllowSorting="true" EmptyDataText="No Ha

我正在开发一个gridview,您可以通过一个按钮下载多个文件

以下是我的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>

每当我单击“Descargar”行命令时,我最初使用的是:

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>");
                }
            }
if(e.CommandName==“Descargar”)
{
DataTable dt=ConexionBD.getInstanceAconExionBD().GetArchivosPorMensaje(Convert.ToInt32(e.CommandArgument));
foreach(数据行dr在dt.行中)
{
字符串strArchivo=dr[“Nombre”].ToString();
string strExtension=Path.GetExtension(strArchivo.ToLower();
Write(“window.open('/Archivos/“+strArchivo+”);”;
}
}
当我点击时,如果那一行有1个pdf,1个jpg和1个文档,它会在另一个窗口中打开pdf和jpg,文档会被下载。这正是我想要的。然而,我注意到每当打开一个新页面时(在pdf和jpg的情况下),页面中的所有字体都会改变。所以我想找到一个解决方案,然后我尝试了这个:

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>");
                }
            }
if(e.CommandName==“Descargar”)
{
DataTable dt=ConexionBD.getInstanceAconExionBD().GetArchivosPorMensaje(Convert.ToInt32(e.CommandArgument));
foreach(数据行dr在dt.行中)
{
字符串strArchivo=dr[“Nombre”].ToString();
string strExtension=Path.GetExtension(strArchivo.ToLower();
RegisterStartupScript(this.GetType(),“myFileOpenScript”,“window.open('/Archivos/“+strArchivo+”);”);
}
}
当我打开一个pdf文件时,字体这次不会改变,但是,它只会打开/下载第一个出现在int dt.Rows[0]中的文件(不会打开上的dt.Rows[1])。我假设Response.Write可以部署多次,但是ClientScript.RegisterStartupScript可能只能执行一次

有没有其他方法可以让我不改变页面的字母字体,只需单击一下就可以打开多个文件

或者如何多次执行ClientScript.RegisterStartupScript


提前谢谢

多了解一些信息会有帮助的。不限制您多次使用RegisterStatupScript,但限制您多次注册相同的类型/键组合(这是一项功能,而不是限制)

如果需要注册不同的脚本,请使用唯一的密钥。如果您只是在进行回发,那么重新注册启动脚本将/应该可以工作


相反。最后一个参数(布尔值)告诉它为您创建
脚本
标记,这样脚本参数就可以只包含您的代码,而不用担心标记。

避免使用
响应是正确的。在这样的事件处理程序中编写
:它在页面生命周期的
呈现
阶段之前执行,并因此在HTML页面的顶部输出


您可以使用
StringBuilder
foreach DataRow
循环中构建脚本,然后注册一次。

因为Jamie Tores answer缺少示例

这是正确的

ScriptManager.RegisterStartupScript(Page, GetType(), "setDatePickerStartDate", "javascript:setDatePickerStartDate('" + s_capstoneStartDate + "'); ", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "setDatePickerEndDate", "javascript:setDatePickerEndDate('" + s_capstoneEndDate + "'); ", true);
这是错误的,因为第三个参数在这两种情况下是相同的

 ScriptManager.RegisterStartupScript(Page, GetType(), "Javascript", "javascript:setDatePickerStartDate('" + s_StartDate + "'); ", true);
 ScriptManager.RegisterStartupScript(Page, GetType(), "Javascript", "javascript:setDatePickerEndDate('" + s_EndDate + "'); ", true);

我通常使用这个方法来显示警报,我可以随时调用它

public class BasePage : System.Web.UI.Page {
        public void ShowNotif(string sMessage) {
            ScriptManager.RegisterStartupScript(Page, GetType(), Guid.NewGuid().ToString(), "alert('" + sMessage.Replace("'", "\'") + "'); ", true);
        }
}
这意味着我可以多次运行Javascript代码

用法:每个Webform类,按如下方式扩展BasePage:

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

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

我知道我参加聚会有点晚了,但我需要完成同样的事情。知道@JaimeTorres提供了一个唯一的键,我只是做了一个静态方法,你在其中传递页面和消息,该方法创建一个带有基本Do的仲裁“键”……同时循环并不断检查这些键,直到我们找到第一个尚未使用的键。然后它使用它来显示消息。对我来说效果很好,也许其他人可以利用它,如果他们找到这个答案

    /// <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);
    }
//
///在传入页面上显示基本消息框
/// 
///要在其上显示消息的页面对象
///要显示的消息
/// 
公共静态ShowMessageBox(页面,字符串消息)
{
类型cstype=page.GetType();
//从Page类获取ClientScriptManager引用。
ClientScriptManager cs=page.ClientScript;
//查找第一个未注册的脚本编号
int ScriptNumber=0;
bool scriptregisted=false;
做
{
ScriptNumber++;
ScriptRegistered=cs.IsStartupScriptRegistered(cstype,“PopupScript”+ScriptNumber);
}while(ScriptRegistered==true);
//执行我们找到的新脚本编号
cs.RegisterStartupScript(cstype,“PopupScript”+ScriptNumber,“警报(“+”消息+“);”),true
            ShowNotif("Hello");
            ShowNotif("World");
            ShowNotif("Any message");
            ShowNotif("Message again");
    /// <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);
    }