繁体   English   中英

如何将C#代码正确地嵌入C#.net页面中包含的JavaScript块中?

[英]How to Embed C# code correctly inside JavaScript Block contained within a C#.net Page?

我基本上是在合并我的Google地图网络应用程序的两个功能。 但是我需要后端可以访问的坐标,所以我制作了一个Data Table ,然后将其传递给javascript。

但是,当我合并代码时,我遇到了一些语法问题(很可能是)。

更新:我得到的错误是Operator '+' cannot be applied to operands of type 'string' and 'method group'

更新#2:请参见下面的Page_Load代码(如果从该代码中触发,则创建数据表和执行主代码)

更新#3:添加了主页代码。 现在Microsoft JScript runtime error: The value of the property 'initialize' is null or undefined, not a Function objectMicrosoft JScript runtime error: The value of the property 'initialize' is null or undefined, not a Function object

在第var myLatLng = new google.maps.LatLng(" tblPoints.Rows[i][0].ToString @", " + tblPoints.Rows[i][1].ToString + @"); 我收到一些与@“&”;的打开/关闭有关的奇怪错误。

任何答案/建议都是可取的。谢谢。

主页的代码(在其中调用JS函数):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>maps integ</title>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <div id="map_canvas" style="width: 100%; height: 100%;"></div>
        <script type="text/javascript">
            window.onload = function (e) {
                initialize();
            }
        </script>
    </form>
</body>
</html>

主页中Page_Load代码:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Latitude"));
            dt.Columns.Add(new DataColumn("Longitude"));
            dt.Columns.Add(new DataColumn("Info"));

            DataRow row = dt.NewRow();
            row["Latitude"] = 28.483109;
            row["Longitude"] = 77.107756;
            row["Info"] = "INFO #1";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Latitude"] = 28.483243;
            row["Longitude"] = 77.107624;
            row["Info"] = "INFO #1";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Latitude"] = 28.483293;
            row["Longitude"] = 77.107579;
            row["Info"] = "INFO #1";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Latitude"] = 28.483359;
            row["Longitude"] = 77.107536;
            row["Info"] = "INFO #1";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["Latitude"] = 28.483559;
            row["Longitude"] = 77.107273;
            row["Info"] = "INFO #1";
            dt.Rows.Add(row);

            //row = dt.NewRow();
            //row["Latitude"] = 28.4804;
            //row["Longitude"] = 77.1251;
            //dt.Rows.Add(row);

            js.Text = GPSLib.PlotGPSPoints(dt);
        }
    }

类文件的代码:

public static class GPSLib
{
    public static String PlotGPSPoints(DataTable tblPoints)
    {
        try
        {
            String Locations = "";
            String sJScript = "";
            int i = 0;


            foreach (DataRow r in tblPoints.Rows)
            {
                // bypass empty rows 
                if (r["latitude"].ToString().Trim().Length == 0)
                    continue;

                string Latitude = r["latitude"].ToString();
                string Longitude = r["longitude"].ToString();

                // create a line of JavaScript for marker on map for this record 
                Locations += Environment.NewLine + @"
                path.push(new google.maps.LatLng(" + Latitude + ", " + Longitude + @"));

                var marker" + i.ToString() + @" = new google.maps.Marker({
                    position: new google.maps.LatLng(" + Latitude + ", " + Longitude + @"),
                    title: '#' + path.getLength(),
                    map: map
                });";

                i++;

            }

            // construct the final script
            // var cmloc = new google.maps.LatLng(33.779005, -118.178985);

            // map.panTo(curmarker.position); //zooming on current marker's posn.
            // map.panTo(myOptions.getPosition());
            sJScript = @"<script type='text/javascript'>

            var poly;
            var map;

            function initialize() {
                var cmloc = new google.maps.LatLng(28.483243, 77.107624);
                var myOptions = {
                    zoom: 19,
                    center: cmloc,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);


                var polyOptions = {
                    strokeColor: 'blue',
                    strokeOpacity: 0.5,
                    strokeWeight: 3
                }
                poly = new google.maps.Polyline(polyOptions);
                poly.setMap(map);

                var path = poly.getPath();

               " + Locations + @"

                    }

            final initPoints(){
         //  var map;
            var infowindow;

            var mapOptions = {
                zoom: 19,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: centr
             };

            map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
            infowindow = new google.maps.InfoWindow();
            drop();


            }

        function drop() {
            for (var i = 0; i < "+ tblPoints.Rows.Count + @"; i++) {
        var myLatLng = new google.maps.LatLng("+ tblPoints.Rows[i][0].ToString+ @", "+ tblPoints.Rows[i][1].ToString + @");
        var mark = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });
    iWindow(mark, "+ tblPoints.Rows[i][2].ToString +@");
   }
}

function iWindow(marker, title) {
    google.maps.event.addListener(marker, 'click', function () {

        infowindow.setContent(title);
        infowindow.open(map, marker);
    });
}
                </script>";
            return sJScript;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

为什么不使用String.Format代替这些串联。 它看起来更好,更易于维护,并且很可能会解决您的问题?

更新1 :您确定以下代码无法完成这项工作吗?

更新2 :现在在开头创建drop函数

更新3 :好的,这是我的下一个更新:)

我提供给您使用this.Page.ClientScript.RegisterStartupScript而不是使用文字将脚本添加到页面。 我也在GPSLib中进行了一些修复。 所以这是Page_Load()

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Latitude"));
        dt.Columns.Add(new DataColumn("Longitude"));
        dt.Columns.Add(new DataColumn("Info"));

        DataRow row = dt.NewRow();
        row["Latitude"] = 28.483109;
        row["Longitude"] = 77.107756;
        row["Info"] = "INFO #1";
        dt.Rows.Add(row);

        row = dt.NewRow();
        row["Latitude"] = 28.483243;
        row["Longitude"] = 77.107624;
        row["Info"] = "INFO #1";
        dt.Rows.Add(row);

        row = dt.NewRow();
        row["Latitude"] = 28.483293;
        row["Longitude"] = 77.107579;
        row["Info"] = "INFO #1";
        dt.Rows.Add(row);

        row = dt.NewRow();
        row["Latitude"] = 28.483359;
        row["Longitude"] = 77.107536;
        row["Info"] = "INFO #1";
        dt.Rows.Add(row);

        row = dt.NewRow();
        row["Latitude"] = 28.483559;
        row["Longitude"] = 77.107273;
        row["Info"] = "INFO #1";
        dt.Rows.Add(row);

        //row = dt.NewRow();
        //row["Latitude"] = 28.4804;
        //row["Longitude"] = 77.1251;
        //dt.Rows.Add(row);

        var script = GPSLib.PlotGPSPoints(dt);

        this.Page.ClientScript.RegisterStartupScript(
            this.GetType(),
            "focus",
            script, false);
    }
}

这是GPSLib

public static class GPSLib
{
    public static String PlotGPSPoints(DataTable tblPoints)
    {
        try
        {
            StringBuilder locations = new StringBuilder();
            StringBuilder drop = new StringBuilder();

            //function drop() {{
            //    for (var i = 0; i < {1}; i++) {{
            //    var myLatLng = new google.maps.LatLng({2}, {3});
            //    var mark = new google.maps.Marker({{
            //        position: myLatLng,
            //        map: map,
            //    }});
            //    iWindow(mark, {4});
            //    }}
            //}}

            drop.AppendFormat(@"function drop() {{{0}", Environment.NewLine);
            int i = 0;
            foreach (DataRow r in tblPoints.Rows)
            {
                // bypass empty rows 
                if (r["latitude"].ToString().Trim().Length == 0)
                    continue;

                string latitude = r["latitude"].ToString();
                string longitude = r["longitude"].ToString();
                string info = r["info"].ToString();

                // create a line of JavaScript for marker on map for this record 
                locations.AppendFormat(@"{0}path.push(new google.maps.LatLng({1}, {2}));

        var marker{3} = new google.maps.Marker({{
            position: new google.maps.LatLng({1}, {2}),
            title: '#' + path.getLength(),
            map: map
        }});", Environment.NewLine, latitude, longitude, i);

                drop.AppendFormat(@"var myLatLng{0} = new google.maps.LatLng({1}, {2});
        var mark{0} = new google.maps.Marker({{
        position: myLatLng{0},
        map: map,
        }});
        iWindow(mark{0}, '{3}');", i, latitude, longitude, info);

                i++;

            }

            drop.Append("}");

            // construct the final script
            // var cmloc = new google.maps.LatLng(33.779005, -118.178985);

            // map.panTo(curmarker.position); //zooming on current marker's posn.
            // map.panTo(myOptions.getPosition());
            string sJScript = string.Format(@"<script type='text/javascript'>

    var poly;
    var map;

    function initialize() {{
        var cmloc = new google.maps.LatLng(28.483243, 77.107624);
        var myOptions = {{
            zoom: 19,
            center: cmloc,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }};

        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);


        var polyOptions = {{
            strokeColor: 'blue',
            strokeOpacity: 0.5,
            strokeWeight: 3
        }}
        poly = new google.maps.Polyline(polyOptions);
        poly.setMap(map);

        var path = poly.getPath();

        {0}

    }}

    function initPoints(){{
        //  var map;
        var infowindow;

        var mapOptions = {{
            zoom: 19,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: centr
            }};

        map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);
        infowindow = new google.maps.InfoWindow();
        drop();
    }}

    {1}

    function iWindow(marker, title) {{
        google.maps.event.addListener(marker, 'click', function () {{

            infowindow.setContent(title);
            infowindow.open(map, marker);
        }});
    }}
    </script>", locations, drop);
            return sJScript;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

这是我的aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <script type="text/javascript">
            window.onload = function (e) {
                initialize();
            }
        </script>
    </form>
</body>
</html>

您忘记了一些“ +”,正确的行是

var myLatLng = new google.maps.LatLng(" + tblPoints.Rows[i][0].ToString + @", " +
                   tblPoints.Rows[i][1].ToString + @");

编辑:

您还忘记了ToString之后的() ,更正:

var myLatLng = new google.maps.LatLng(" + tblPoints.Rows[i][0].ToString() + @", "
                 + tblPoints.Rows[i][1].ToString() + @");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM