Usando jQuery con Razor en ASP MVC

In my view I have this code

<a href="#" class="bt_on" title="ON">ON</a>
<script type="text/javascript">switchOnOff()</script>

And I have this jQuery code in a file named "on-off-button.js"

$(function switchOnOff () {
  $("a.bt_off").click(function () {
    $(this).removeClass().addClass("bt_on");
  });
  $("a.bt_on").click(function () {
      $(this).removeClass().addClass("bt_off");
  });
});

And to wire all this I put this in my layout file

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

Now When I load my page, I het an exception from Microsoft JScript saying that the value of the property is Null or Not Defined, not a Function object

Qué me estoy perdiendo ?

Gracias.

preguntado el 10 de marzo de 12 a las 12:03

Are you sure that function switchOnOff() is visible to code in your view? You create it and pass to jquery. I don't think it is visible to your view. Also I don't understand why are you calling it yourself when you already add it to jquery's document.ready. -

2 Respuestas

Your View cant see the .js file for some reason.

Pruebe lo siguiente:

<script src="../../Scripts/on-off_button.js" type="text/javascript"></script> 

respondido 10 mar '12, 12:03

No that's not the problem, besides I thought that I should never put static Urls like this in my code. - kbaccouche

use this maybe solve:

function switchOnOff() {
$("a .bt_off").click(function() {
    $(this).removeClass().addClass("bt_on");
});
$("a .bt_on").click(function() {
    $(this).removeClass().addClass("bt_off");
});

}​ or

function switchOnOff() {
$('.bt_off').click(function() {
    $(this).removeClass().addClass("bt_on");
});
$('bt_on').click(function() {
    $(this).removeClass().addClass("bt_off");
});

}​

respondido 10 mar '12, 12:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.