0

Forgive me for my lack of MVC knowledge - still in the process of teaching myself.

Basically started a new job which they primarily use MVC, learning curve is steep. Iv'e been tasked with calling a Javascript file when required in a nested partial view, Whilst I'm comfortable with the former, I seem to be having trouble with loading the script. I've tried sections which didn't work to well and I believe cannot be done.

So I have: Index.cshtml > Loads in AddressList.cshtml > which loads in Address.cshtml

When the address.chtml partial view has been loaded, I'd like to load the js file.

<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?sensor=false'></script>

This is very trivial to some but never the less cannot seem to get it to work.

The task at hand is part of a much larger feature which I've built and works great when loading the js file in the main layout view. Circumstances have changed and now the js file needs to be moved.

Any help greatly appreciated.

Tez Wingfield
  • 2,129
  • 5
  • 26
  • 46
  • I know very little about .Net. However is it possible to place the script tag and the bottom of your address.cshtml so that it loads after the elements inside of your address.cshtml file loads? – Larry Lane Mar 03 '16 at 11:56
  • Here is a link to another question that may help if you decide to load JavaScript in your partial views. http://stackoverflow.com/questions/11098198/is-it-ok-to-put-javascript-in-partial-views – Larry Lane Mar 03 '16 at 12:01

1 Answers1

0

Javascript and PartialViews don't work well together, since you can use your PartialView multiple times and, if you add your PartialView twice, the script will also be.

One way to get around is moving your script section to your main view, which calls your PartialView later in the process.

Or, if you don't mind on using third party frameworks, there is ForLoop HtmlHelper which allows you to use javascript inside a PartialView and control the scripts to be added correctly.

Thiago Ferreira
  • 661
  • 3
  • 19