1

I have main view which includes another partial view. Partial view should show google maps piece in 'div'.

When I have 'div' in main view - works.

When I try to update 'div' in partial view - 'div' is empty, no errors.

Partial view is loaded by Ajax call on the button click.

Is there way to show google map in partial view, when partial view needs to be loaded during main view load by ajax call?

Many thanks

WORKS

main.cshtml

<div id="map_canvasMain" style="height:200px;width:200px;">
</div>


@section scripts{
<section class="scripts">

<script type="text/javascript">

     $(document).ready(function () {
        loadMyPartialView('@Model.Id'); // must be here, need to load partial view

        InitializeGoogleMap(); 
});

function InitializeGoogleMap() {
..........
    // This makes the div with id "map_canvasMain" a google map 
    var map = new google.maps.Map(document.getElementById("map_canvasMain"), mapOptions);
    ..........
}

function loadMyPartialView() {   
    $.ajax({
    type: "POST",
    url: '/Association/MyPartialView'       
    success: function (data) {
    $("#divMyPartialViewContent").html(data);
    }
    });  // AJAX call
}


 </script>
 </section>
 }

Does NOT work: MyPartialView.cshtml

@section scripts{
<section class="scripts">

<script type="text/javascript">

     $(document).ready(function () {

        InitializeGoogleMap(); 
});

function InitializeGoogleMap() {
..........
    // This makes the div with id "map_canvasMain" a google map 
    var map = new google.maps.Map(document.getElementById("map_canvasInPartial"), mapOptions);
    ..........
}

</script>
</section>
}

Karen Slon
  • 233
  • 1
  • 4
  • 16
  • Scripts should **never** be in partials. And `@section scripts {` is not even supported in partials so you script would never execute anyway –  Feb 21 '18 at 22:29
  • @Emilia, Its bad practice for many reasons. Partials are often used multiple time in views, or may be loaded multiple times via ajax calls - so you end up duplicating scripts. It means that you end up with in-line scripts making it harder to debug and the scripts may be loaded in the wrong order. If the partial also includes reference to jquery or other plugins, you risk wiping out other scripts that are in the main view. –  Mar 19 '18 at 04:21

0 Answers0