So, continuing in climbing my MVC learning curve, I would like to know how to effectivelly handle javascript in partial views. I mean coding a开发者_如何学Python script in a partial view and then rendering the partial view twice in a view gives duplicate code, including variables and is generally conflictive.
How pros handle JS concurrency in ASP.NET MVC so each partial view see only its own JS code?
When you render a partial view within a view, you can still reference all of the HTML elements in that partial view from Javascript on the holding view.
This will not only help with duplication, but will add to the principle that code should be maintainable within one place in the codebase.
If I were you, I would put all Javascript that your partial views need in the main view, or better yet, in a Javascript file that is separate and reference it in a master page which your main view inherits from :)
This video gave me a great inside look into jquery with mvc it share also some best-practise...
mvcConf 2 - Eric Sowell: Evolving Practices in Using jQuery and Ajax in ASP.NET MVC Applications
http://channel9.msdn.com/Series/mvcConf/mvcConf-2-Eric-Sowell-Evolving-Practices-in-Using-jQuery-and-Ajax-in-ASPNET-MVC-Applications
def. worth a look...
Use external javascript file and reference it only in the full view. Put this line in the partial view so it does not load the stuff from the _Layout.cshtml
@{ this.Layout = null; }
you need to add the script at the bottom of the page before close the body tag place all required js their and place a rendersection('yoursection',false) so when you need you can define your section and just use the script their who would work in the page you need to define.
If you want javascript need to maintained effectively. Write that javascript in seperate js file. create another partial view and give the link to the js file. while rendering partial views, render the partial view which contains the link for that js file
I am not sure if it is the best way of doing this, but I certainly got it working for me.
So you write you javascript in an external file, and reference it in a partial view, then you could nest your partial view inside this partial view, so each of those nested partial view will be able to use the java script file on their parent level. So this way, you only reference the javascript once, but it can be used with all nested partial views.
good luck mate.
I think Dan Finch and user2745484 have answered the question. But as you sad scripts in partial views may override each other. For solving these problem you need to use some kind of object oriented programming to have encapsulation. Note that you may encounter these kind of problem everywhere you write JavaScript code.
精彩评论