简体   繁体   中英

MVC Partial Views and Javascript

I have a partial view which is essentially a widget. I want to have between 1 and 'n' of these on the same page.

My issue I'm having is I can't get javascript to execute in each one.

eg

Index.cshtml

<div>
   @Html.Partial("_ButtonPartialView")
    <br/>
    <br />
   @Html.Partial("_ButtonPartialView")
</div>

_ButtonPartialView.cshtml

<h2>ButtonView</h2>
<button id="foo">
    on
</button>

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/test").Include(
                        "~/Scripts/test.js"));

Layout.cshtml

@Scripts.Render("~/bundles/test")

test.js

$(document).ready(function() {
    $('#foo').click (function() {
        if ($('#foo').html() === 'on') {
            $('#foo').html('off');
        } else {
            $('#foo').html("on");
        }
    });
});

My problem is, when i click the first button it switches between on and off fine. When I click the second button, nothing happens!

My bigger issue, if I can get this to work is. I obviously want all my Partial Views to be independent. eg I don't want to click one button and they all trigger. They are all going to be passed a model and I need to write JS that will do stuff with that model and display the information.

So each widget needs to be independent.

Thanks

As mentioned in the comments, the id must be unique. If you want to reference the button by id you'll need to generate unique ids.

A cleaner way is to use a class selector instead with $(this) to reference the button instance that triggered the event.

$(".foo").on("click", function(e) {
    var btn = $(this);
    var state = btn.html();
    ...
});

to trigger script on dynamically added content you need to tie the event to the document. change your click event to

$(document).on('click', '#foo', function() {
    if ($('#foo').html() === 'on') {
        $('#foo').html('off');
    } else {
        $('#foo').html("on");
    }
});

then as mentioned in the other answer change the selector to be partial specific

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