【问题标题】:ASP.NET MVC5 How to dynamically fill an Iframe src based on data in the modelASP.NET MVC5 如何根据模型中的数据动态填充 Iframe src
【发布时间】:2015-10-28 19:45:30
【问题描述】:

希望有好心人可以在这里帮助初学者编码:)

我有一个 ASP MVC 应用程序,其目的是采取

  1. 地址作为用户输入,
  2. 动态构建对 Google MAPS api 的查询以进行编码和距离计算
    1. 反序列化返回的 JSON 并使用坐标和距离计算填充数据。

我有这么多工作正常。我现在正在尝试根据存储在模型中的数据,在我的视图/控制器中的详细信息操作上动态构建要在 Iframe 中使用的 URL,并使用它来显示嵌入式 Google MAPS 窗口。

My Journey 模型声明 mapurl 变量如下: 公共字符串 mapurl { 获取;放; }

我的 JourneyController 如下填充这个字符串变量:

string mapurl = String.Format("https://www.google.com/maps/embed/v1/directions?key=MYKEY&origin={0}&destination={1}", Journey.StartAddress, Journey.FinishAddress);

当我在这一行之后设置断点时,我可以看到代码正在填充 mapurl 字符串值,如下所示:

https://www.google.com/maps/embed/v1/directions?key=MYKEY&origin=XYZ Lawn, Raheny, Dublin, Ireland&destination=Enniscorthy Co. Wexford, Ireland。

另请注意,在代码的早期阶段,最初设置为用户输入值的 StartAddress 和 FinishAddress 字符串变量后来被设置为来自 Google MAPs API 的 JSON 中发回的“格式化地址”值,因此这些应该是值(尽管,请参阅下面我的“预感”评论行,可能格式不正确)应该是对 Google 地图令人敬畏的有意义的地址。

在我的详细信息视图中,我尝试动态设置 iframe URL 值,如下所示:

    <iframe width="500" height="350" frameborder="0" style="border:0"      src="@Model.mapurl"></iframe>

对于背景信息,以下静态 iframe URL 代码已成功加载。

    <iframe width="500" height="350" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/directions?origin=1%20Foxfield%20Lawn2C%20Raheny%2C%20Ireland&destination=128%20Old%20County%20Road%2C%20Crumlin%2C%20Ireland&key=MYKEY" allowfullscreen></iframe>

我有一种预感,问题在于声明 mapurl 字符串变量的代码不是“URL 转义”,因为其中包含空白字符,这些空白字符在生成的 URL 字符串中无效。

非常感谢您提供的有关如何更新设置 mapurl 值的代码以解决此问题的任何帮助建议

【问题讨论】:

    标签: asp.net asp.net-mvc iframe


    【解决方案1】:

    尝试使用@Uri.EscapeDataString(Model.mapurl);

    【讨论】:

      【解决方案2】:

      不能 100% 确定为什么接受的答案随后会被查询,但如果它对其他用户有用,这里是一个更完整的解决方案 在 Journey 控制器上的 Create [POST] 方法中,我需要使用 @Uri.EscapeDataString () 方法来清除 mapurl 变量中的空格

          journey.mapurl = String.Format("https://www.google.com/maps/embed/v1/directions?key=MYKEY&origin={0}&destination={1}", @Uri.EscapeDataString(journey.StartAddress), @Uri.EscapeDataString(journey.FinishAddress));
      

      然后,URL 被正确地格式化为 HTML 格式,并在 IFRAME 中按预期显示,使用现有的 HTML 作为

            <iframe width="500" height="350" frameborder="0" style="border:0"      src="@Model.mapurl"></iframe>
      

      【讨论】:

        猜你喜欢
        • 2013-08-09
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 2016-12-11
        相关资源
        最近更新 更多