如何在 handler.ashx 文件中使用 ScriptManager.RegisterStartUpScript 调用 javascript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7730107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:05:58  来源:igfitidea点击:

how can i call javascript functions with ScriptManager.RegisterStartUpScript inside handler.ashx file?

c#javascriptasp.nethandlerscriptmanager

提问by SilverLight

i have a repeater like below :

我有一个像下面这样的中继器:

                    <asp:Repeater ID="Repeater1" runat="server">
                        <ItemTemplate>
                            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("FilePath","~/HandlerForRepeater.ashx?path={0}") %>'><%# Eval("FileName")%></asp:HyperLink>
                            <br />
                            <asp:Label ID="Label3" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FileCreationDate", "{0:tt h:m:s - yyyy/MM/dd}") %>'></asp:Label>
                            <hr />
                        </ItemTemplate>
                    </asp:Repeater>

i have an HandlerForRepeater.ashx for save as dialog like below :

我有一个 HandlerForRepeater.ashx 用于另存为对话框,如下所示:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace FileExplorer
    {
        /// <summary>
        /// Summary description for HandlerForRepeater
        /// </summary>
        public class HandlerForRepeater : IHttpHandler, System.Web.SessionState.IRequiresSessionState
        {

            private HttpContext _context;
            private HttpContext Context
            {
                get
                {
                    return _context;
                }
                set
                {
                    _context = value;
                }
            }

            public void ProcessRequest(HttpContext context)
            {
                Context = context;
                string filePath = context.Request.QueryString["path"];
                filePath = context.Server.MapPath(filePath);

                if (filePath == null)
                {
                    return;
                }

                System.IO.StreamReader streamReader = new System.IO.StreamReader(filePath);
                System.IO.BinaryReader br = new System.IO.BinaryReader(streamReader.BaseStream);

                byte[] bytes = new byte[streamReader.BaseStream.Length];

                br.Read(bytes, 0, (int)streamReader.BaseStream.Length);

                if (bytes == null)
                {
                    return;
                }

                streamReader.Close();
                br.Close();
                string fileName = System.IO.Path.GetFileName(filePath);
                string MimeType = GetMimeType(fileName);
                string extension = System.IO.Path.GetExtension(filePath);
                char[] extension_ar = extension.ToCharArray();
                string extension_Without_dot = string.Empty;
                for (int i = 1; i < extension_ar.Length; i++)
                {
                    extension_Without_dot += extension_ar[i];
                }

                //if (extension == ".jpg")
                //{ // Handle *.jpg and
                //    WriteFile(bytes, fileName, "image/jpeg jpeg jpg jpe", context.Response);
                //}
                //else if (extension == ".gif")
                //{// Handle *.gif
                //    WriteFile(bytes, fileName, "image/gif gif", context.Response);
                //}

                if (HttpContext.Current.Session["User_ID"] != null)
                {
                    WriteFile(bytes, fileName, MimeType + " " + extension_Without_dot, context.Response);
                }
                else
                {
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "MyMethod", "alert('You Can Not Download - pzl Login First');", true);
                }
            }

            private void WriteFile(byte[] content, string fileName, string contentType, HttpResponse response)
            {
                response.Buffer = true;
                response.Clear();
                response.ContentType = contentType;

                response.AddHeader("content-disposition", "attachment; filename=" + fileName);

                response.BinaryWrite(content);
                response.Flush();
                response.End();
            }

            private string GetMimeType(string fileName)
            {
                string mimeType = "application/unknown";
                string ext = System.IO.Path.GetExtension(fileName).ToLower();
                Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
                if (regKey != null && regKey.GetValue("Content Type") != null)
                    mimeType = regKey.GetValue("Content Type").ToString();

                    return mimeType;
                }

                public bool IsReusable
                {
                    get
                    {
                        return false;
                    }
                }
            }
        }

every thing is ok about this handler , but i want to show an alert to my users if Session["User_ID"] is Null!
so my problem is in below line :

这个处理程序的一切都很好,但是如果 Session["User_ID"] 为 Null,我想向我的用户显示警报!
所以我的问题在下面一行:

System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "MyMethod", "MyMethod();", true); 

and this line has error in this hadler!
how can i call such these javascript methods in HandlerForRepeater.ashx?

这条线在这个hadler中有错误!
我如何在 HandlerForRepeater.ashx 中调用这些 javascript 方法?

thanks in advance

提前致谢

回答by Justin

You should be doing that from the page your repeater control is on not the handler. In the code behind for the page with repeater:

您应该从转发器控件所在的页面而不是处理程序中执行此操作。在带有转发器的页面后面的代码中:

if(HttpContext.Current.Session["User_ID"] != null)
{
    Response.Redirect("~/HandlerForRepeater.ashx?path={FilePath}");
}
else
{
    ClientScript.RegisterStartupScript(this.GetType(), "MyMethod", "MyMethod();", true);
}

You can just output the file from that page but trying to stick to your current example as much as possible.

您可以只从该页面输出文件,但尽量坚持当前的示例。