0

I want to integrate my javascript file in my asp.net mvc app but when adding my .js file in the scripts folder and then placing the following line in my view, there is an error. I think that is because I do not have to place it in the but in the , but not in _layout.cshtml because it does not appear in all pages.

  <script src="@Url.Content("~/Scripts/test.js")" type="text/javascript"></script>

Here is my script:

cars = new Array("Mercedes", "Volvo", "BMW", "porche");
phones = new Array('Samsung', 'Nokia', 'Iphone');
names = new Array('Kasper', 'Elke', 'Fred', 'Bobby', 'Frits');
colors = new Array('blue', 'green', 'yellow');

populateSelect();

$(function () {

$('#cat').change(function () {
    populateSelect();
});

});

    function populateSelect() {
   cat = $('#cat').val();
   $('#item').html('');

   eval(cat).forEach(function (t) {
    $('#item').append('<option>' + t + '</option>');
  });
  }

So first can you tell me what is wrong with my .js file and is it relevant to use javascipt or do I have to use Ajax( I hope no) ?

The script is for populating a dropdownlist based on the choice of the previous one, then can you help me how to do if I want to populate theses dropdownlist using data in SQL server ?

Thank you for your help

intern
  • 225
  • 1
  • 3
  • 14
  • First you should use ' instead of " for src attribute (src='@Url.Content("~MyPath/My.js")'), second what's the error you got ? – Luca Aug 25 '14 at 13:22

1 Answers1

0

The recommended way is to define a section at the end of your view

@section js
{
   <script src="~/Scripts/test.js" type="text/javascript"></script>
}

Then in your _layout.cshtml at the end include the script like this :

    @RenderSection("js", false)
</body>

You could try to pull out the script and the event handler registration out of the ready handler.

cars = new Array("Mercedes", "Volvo", "BMW", "porche");
phones = new Array('Samsung', 'Nokia', 'Iphone');
names = new Array('Kasper', 'Elke', 'Fred', 'Bobby', 'Frits');
colors = new Array('blue', 'green', 'yellow');

function populateSelect() {
    cat = $('#cat').val();
    $('#item').html('');

    eval(cat).forEach(function (t) {
        $('#item').append('<option>' + t + '</option>');
    });
}

$('#cat').change(function () {
    populateSelect();
});

populateSelect();

That should work too

Robert
  • 724
  • 5
  • 7
  • Thank you it works now! Do you have any idea about the second part of the question ? – intern Aug 25 '14 at 14:21
  • If you are using a dropdown list check this http://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example I am not quite sure what your Problem is. – Robert Aug 25 '14 at 16:54