views:

307

answers:

2

I am developing an application using Asp.net mvc and jquery. I'd like to use the same naming convention (classes and ids) for html elements in different views.

In case when I want to load a partial view asynchronously, the $(document).ready() piece of code in the main view loses its usefulness because none of the patial view's html tags and css naming is recognized by jquery. I certainly do not want to write the same code for every view. What's th ebest way to solve this issue?

+4  A: 

You can use .live() for this, for example:

$(".myClass").click(function() { });

Becomes this:

$(".myClass").live('click', function() { });

.live() works in a different way. .click() binds to the elements the selector matched when it ran, usually document.ready. .live() works by living at the DOM root, listening for events to bubble and executing the handler if the event that bubble's target matches the selector.

Nick Craver
it works for clicks !!! What about plugins that elements in different partial views use ? For example, the dataTable() jquery plugin must work for all elements that have a class="grid" regardless of the view that they're coming from
If I understand your question correctly that's no problem. You can use $(".grid").live([eventname], function() {})... in the document ready to "bind" it to any event in any partial view you use.
Rody van Sambeek
@user252160 - How are you loading these `$.ajax`?
Nick Craver
The thing is that I want my tables to be "gridified" whenever the main page or the partial view resp. is loaded
If using live is not working for the gridify-plugin you could include the call to gridify in the partial. But you have to keep the "live" for the click-event.Apart from that: live was enhanced to listen to more events and have a new context option in 1.4. http://api.jquery.com/live/
Malcolm Frexner
A: 

I personally just load all the content using my own wrappers around $.post, and initiallize content there as needed. This also helps to unify handling errors, waiting notifications, etc.

Third-party libraries usually provide a way to pre-process ajax-loaded content, too.

Partial views won't call document.ready, but they will evaluate scripts inside script tags in head, so that's how you can force invocation of partial view specific scripts.

Another way that I use is custom html tags on forms. E.g.

<form custom-setup="MyCustomSetupFunc">

and my $.post handler will check for this tag and call this function, passing the form instance. This helps to narrow the scope of the script when partial is loaded (useful when several instances of partial can be loaded on same page).

queen3