Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready() and partial view load

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?

like image 902
xantrus Avatar asked Apr 10 '10 18:04

xantrus


People also ask

What is the purpose of $( document ready ()?

$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Is document ready the same as window load?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.

How many time $( document ready (); function we can use in a single document?

Can we add more than one 'document. ready' function in a page? Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

How do I pass a model into partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.


1 Answers

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.

like image 181
Nick Craver Avatar answered Nov 15 '22 04:11

Nick Craver