首页 > 解决方案 > 从 ASP.Net MasterPage 调用 JS 函数

问题描述

我需要从 SQL Server(公司徽标)读取图像数据并将其保存在 localStorage 中。该公司徽标显示在母版页左侧边栏中,以便在每个客户页面中都可见。

为此,我在母版页中使用了 3 个 JS 函数。

function storageCheck() {
  if (localStorage.getItem("imgData") === null) //check availability 
    document.getElementById('<%=hdfStorage.ClientID %>').value = "true"; //assign true to a hidden field
  else
    document.getElementById('<%=hdfStorage.ClientID %>').value = "false";
}

function storelogo(imgData) { //store image data
  localStorage.setItem("imgData", imgData);
}

function getImg() { //get data
  var dataImage = localStorage.getItem('imgData');
  document.getElementById('imgCompanyLogo').src = dataImage;
  alert('got')
}

在母版页后面的代码中,我调用了这些 JS 函数

protected void Page_LoadComplete(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    ScriptManager.RegisterStartupScript(this, this.GetType(), "checkfn", "storageCheck()", true);

    if (hdfStorage.Value == "true")
      ScriptManager.RegisterStartupScript(this, this.GetType(), "storelogoo", "storelogo('" + <Base64String img data from database> + "');", true);
    else if (hdfStorage.Value == "false")
      ScriptManager.RegisterStartupScript(this, this.GetType(), "getlogo", "getImg();", true);
  }
}

我试过把它放在Page_Load活动中,但没有用。我面临的问题是这些函数没有被调用,如果从页面加载事件中调用,当我检查使用时隐藏字段控件将不会获得值hdfStorage.Value == "true"

标签: javascriptc#jqueryasp.netscriptmanager

解决方案


我建议把它作为单例或会话放在内存中,所有人都这样工作


推荐阅读