【问题标题】:Javascript to pass value from server to client doesnt work将值从服务器传递到客户端的 Javascript 不起作用
【发布时间】:2015-07-24 13:59:58
【问题描述】:

我在网络表单中有一个文件上传控件和一个按钮。当我在选择文件上传后单击按钮时,它应该保存图像并使用 GUID 重命名它。

protected void btnUpload_Click(object sender, EventArgs e)
{
    string fileName = string.Empty;
    string filePath = string.Empty;
    string extension = string.Empty;
    try
    {
        //Check if Fileupload control has file in it
        if (FileUpload1.HasFile)
        {
            // Get selected image extension
            extension = Path.GetExtension(FileUpload1.FileName).ToLower();
            //Check image is of valid type or not
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
            {
                //Cretae unique name for the file
                fileName = Guid.NewGuid().ToString() + extension;
                //Create path for the image to store
                HiddenField1.Value = fileName;
                filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
                //Save image in folder
                FileUpload1.SaveAs(filePath);
                //Show the panel and load the uploaded image in image control.
                //pnlCrop.Visible = true;
        }

上面的代码工作得很好,保存图像并将 GUID 传递给 hiddenfield。现在我想将 hiddenfield 的值传递给客户端变量,然后将其显示为警报。

  <script type="text/javascript">
    function showfilename() {       
        setTimeout(function () {
            var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
            alert(dpGUID);
        },3000)
    }
</script>

使用超时的原因?因为我想在按钮单击时为其分配值后读取隐藏字段的值。

注意:我在 Buttonclick 上使用了两个功能。一个在客户端,另一个在服务器端,如下所示:

 <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />

有可能吗?如果是,可能是什么导致了问题?

【问题讨论】:

  • 问题出在哪里?不显示文件名吗?
  • 它没有显示任何警报消息@EnriqueZavaleta
  • 如果您使用的是服务器端而不是页面将提交,那么您尝试这样做的目的是什么?服务器端代码不应该设置您要阅读的任何内容吗?

标签: javascript asp.net hidden-field


【解决方案1】:

尝试使用RegisterClientScriptBlock

protected void btnUpload_Click(object sender, EventArgs e)
{
    /*All your code here*/
    //instead of HiddenField1.Value = fileName; write the line below
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}

现在您可以摆脱 OnClientClick="showfilename()HiddenField

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多