简体   繁体   中英

Unable to run javascript in partial view called using ajax call MVC

I have this JavaScript code in a partial view that gets the Geo-location of a client.

<h1>Map</h1>
<style type="text/css">
    #map-canvas {
        height: 500px;
    }
</style>

<script type="text/javascript"
        src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:'sensor=false'}]}"></script>

<script type="text/javascript">        
    function initialize() {

        var myLatlng = new google.maps.LatLng(37.4219985, -122.0839544);
        var mapOptions = {
            zoom: 12,
            center: myLatlng
        }
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Provider'
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map-canvas"></div>

From another view I am making an Ajax call to load this partial view on an action-link click.

<script>
    $(function () {
        $('.provider-details').on('click', function (e) {

            $.get("/Provider/Map", function (response) {
                $('#map').html(response)
            });

            e.preventDefault();
        })
    });
</script>

I am able to call the partial view, I can see the text; however, the map is not loading. I can see the map if I load the view directly. Any suggestions?

your initialize function is not triggering cause its probably attached to window not the body. just call it after the ajax call succeeds and you're good to go:

$(function () {
    $('.provider-details').on('click', function (e) {

        $.get("/Provider/Map", function (response) {
            $('#map').html(response);
            initialize();
        });

        e.preventDefault();
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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