简体   繁体   中英

Asp.Net MVC JavaScript doesn't work after loading page

I'm developing Asp.Net MVC application. I'm using partial view for menu in Layout form for some views. I need use JavaScript on this view, but its work only on first time - after view loaded. Later - doesn't. Partial View is like this:

@Scripts.Render("~/bundles/jquery")
@Html.CheckBox("IsChoosed", true, new { onclick = "FormReload();" })

<script>
    $(".IsChoosed").on("onchange", function () {
        FormReload();
    });

    var FormReload = new function ()
    {
        alert("FormReload");
    };

</script>

LayoutForm:

@Html.Partial("_ViewPartial")

@RenderBody()

Alert message is displayed after loading of page, when checkbox value set. But after while i'm changing value - doesn't. I tried to move JavaScritp methods to ***.js file and hook up it in view, but its worked the same way. Where can be an error?

Your change event is not firing because you are trying to attach to the class .IsChoosed .

try changing your change handler to:-

$("#IsChoosed").on("onchange", function () {
     FormReload();
});

so #IsChoosed instead of .IsChoosed .

EDIT

Also, change:-

var FormReload = new function ()

to this:-

function FormReload()

@Html.CheckBox("IsChoosed",... - first argument is name .

Selector $(".IsChoosed") looks for class IsChoosed . So onchange callback is not set.

To fix you can do the following:

@Html.CheckBox("IsChoosed", true, new { @class="IsChoosed", onclick = "FormReload();" })

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