eyeballpaul
eyeballpaul

Reputation: 1735

jQuery in a commonly used partial view in MVC3

I was not sure the best way to go about this.

Basically, I have a partial view that may be put on a page multiple times, and in the partial view, it contains jQuery which binds to certain events for things that may happen on the page. For example, button clicks etc.

Now, using jQuery selectors, you would target things on the page using an ID (which I cant do as then multiple things on the page would have the same ID). You could also use class names to be able to select things, but this wont work either, as for each partial view they will all target each other, which cannot happen.

I need each piece of jQuery to only select things from its own partial view. How would I do this?

I can only think of one way to do it, and it seems a bit of a hack. But I could basically create a model, that contains a string, which would be a selector for the container that will surround the partial view. Then in the view it would use the selector as well as the normal classs names it would normall use.

Is there a better way?

Upvotes: 1

Views: 736

Answers (2)

Ali Mohammadi
Ali Mohammadi

Reputation: 21

I think there's an easier way! It's about .parents() jQuery method that you can find parent of a clicked button or etc.

Do this works:

  1. Your partial view must have a div with a certain id (such as "pView") that contains all other elements

  2. In the partial view, give a certain id to the button (such as "btnDelete")

  3. Write your script like this:

    $(document).ready(function() {

    $("#pView #btnDelete").click(function() {
        var partialView = $(this).parents("#pView");
    
        // Now you detect what pView should be deleted!
        // this.parents("#pView") means select the parent with id = "pView"
        // ...
    
    });
    

    });

Upvotes: 0

Mike Gwilt
Mike Gwilt

Reputation: 2449

I would make sure your partial view's content is contained in some sort of uniquely marked div (whether it be id or class or whatever). Limit the scope to that id.

I suppose I would define the Id as, perhaps, var myId = Guid.NewGuid().ToString("N"); at the top of the partial and make sure the partials content content is wrapped in something like <div id="@myId"> ...and then in your jquery make your selector limit the scope to @myId

Upvotes: 1

Related Questions