如何使用razor语法设置javascript变量或调用函数?

时间:2012-05-13 20:13:08

标签: javascript razor visual-web-developer

这是关于网络编程的初学者问题。基本上我有一个页面,使用Google Map API显示默认地址。它可以很好地查找" 221B Baker Street,伦敦,英国",但有一个文本框我希望能够写入一个地址,然后查找它。它是一个cshtml页面,我知道剃刀语法

@{if(IsPost) { do something }}

所以基本上我想从文本框中取出Request.Form["FindAddress"];并将其设置为javascript myAddress变量,以便显示用户地址。但我不知道如何进行内联编码。将IsPost条件放在javascript函数的-tag中时,它会一直给出语法错误。这是完整的页面

<!DOCTYPE html>

<html>

<head id="head">
<title></title>
<link href="@Server.MapPath("~/Styles/Site.css")" rel="stylesheet" type="text/css" />
</head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=<YOUR_API_KEY>&sensor=false"
        type="text/javascript"></script>
<script type="text/javascript">

    var myAddress = "221B Baker Street, London, United Kingdom"; // how do I overwrite this if it is (isPost)?


    var map;
    var geocoder;
    function initialize() {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(51.5, -0.1), 10);
            map.setUIToDefault();

            geocoder = new GClientGeocoder();                   
            showAddress(myAddress);
        }
    }
    function showAddress(address) {
        geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
    }
</script>

<body onload="initialize()" onunload="GUnload()">
    <form id="form1" runat="server">
        <div>
            <input type="text" id="FindAddress" name="FindAddress" />
        </div>
        <div id="map" style="width: 500px; height: 500px"></div>
    </form>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

我没有尝试过以下代码,但我希望它能运作。基本上我把条件检查逻辑放在脚本块之外,并将结果存储在一个变量中,并在javascript中引用。

@{
  var address = "221B Baker Street, London, United Kingdom";

  if (Request.HttpMethod == "POST")
  {
    address = Request.Form["FindAddress"];
  }  
}

  <script type="text/javascript">

    var myAddress = "@address"; // how do I overwrite this if it is (isPost)?


    var map;
    var geocoder;
    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(51.5, -0.1), 10);
        map.setUIToDefault();

        geocoder = new GClientGeocoder();
        showAddress(myAddress);
      }
    }
    function showAddress(address) {
      geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
    }
  </script>