You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharePoint2013:如何在Mapas.ascx中调用ascx.cs的公共变量?

嘿,这事儿其实挺简单的,给你两种常用的实现方式,你可以根据自己的开发习惯来选:

方法一:直接在ASCX页面绑定后台变量

你已经在后台Mapas.ascx.cs里声明了公共变量,那直接在前台Mapas.ascx的iframe标签里用ASP.NET的内嵌表达式<%= %>替换占位符就行,代码示例如下:

<iframe width="600" height="450" frameborder="0" style="border:0" 
        src="https://www.google.com/maps/embed/v1/place?q=place_id:<%= direccion %>&key=<%= apiKey %>" 
        allowfullscreen></iframe>

这里有两个小细节要注意:

  • 一定要确保apiKey和direccion在后台的页面生命周期方法(比如Page_Load)里已经被正确赋值,不然前台会拿到空字符串,地图加载不出来
  • 如果你的direccion包含空格、逗号这类特殊字符,建议对它做URL编码,避免URL格式错误。可以在后台新增一个编码后的变量:
    public string direccionEncoded;
    protected void Page_Load(object sender, EventArgs e)
    {
        // 假设你已经给原始direccion赋值了
        direccionEncoded = HttpUtility.UrlEncode(direccion);
    }
    
    然后前台替换成<%= direccionEncoded %>就好
方法二:后台动态生成Iframe控件

如果你更喜欢完全在后台控制iframe的生成逻辑,可以先在Mapas.ascx里加一个服务器端容器:

<div id="mapContainer" runat="server"></div>

然后在Mapas.ascx.cs里动态创建iframe并设置属性:

protected void Page_Load(object sender, EventArgs e)
{
    // 先确保apiKey和direccion已经被正确赋值
    string mapSrc = $"https://www.google.com/maps/embed/v1/place?q=place_id:{HttpUtility.UrlEncode(direccion)}&key={HttpUtility.UrlEncode(apiKey)}";
    
    HtmlGenericControl iframe = new HtmlGenericControl("iframe");
    iframe.Attributes.Add("width", "600");
    iframe.Attributes.Add("height", "450");
    iframe.Attributes.Add("frameborder", "0");
    iframe.Attributes.Add("style", "border:0");
    iframe.Attributes.Add("src", mapSrc);
    iframe.Attributes.Add("allowfullscreen", "");
    
    mapContainer.Controls.Add(iframe);
}

这种方式的好处是能更灵活地控制iframe,比如根据业务条件动态调整尺寸、显示隐藏,或者修改其他属性。

最后再提两个注意事项:

  • 你已经把变量声明为public了,这没问题,只要不是private,前台就能访问到
  • 记得确认你的Google Maps API Key是有效的,并且已经启用了Embed API,不然地图会加载失败哦

内容的提问来源于stack exchange,提问作者Imrik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:14:43