Loading JQuery in Partial View on MVC

不问归期 提交于 2020-01-16 09:11:10

问题


I have an ASP.NET MVC C# web application.

In my layout file I have the following ajax call

  <li class="PriceModal">
                        @Ajax.ImageActionLink("/InternalDB/Content/downloadCSV.png", "Pareto", "35px", "35px", "PartialViewPriceCalculator",
                        "PriceCalculator", new {@Pareto = "active" }, new AjaxOptions
                        { UpdateTargetId = "PriceCalculator", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"}, new { @style = "padding-top:30px" })
  </li>  

When this Ajax link is clicked a bootstrap Modal is loaded and a partial view is load inside the Bootstrap Modal. At this point the Bootstrap modal and the partial view inside are sitting on top of my existing page.

My problems start when I place jQuery code inside the partial View. I have found a way to append the jQuery code (partial) to the DOM with the following code

 $('body').on('jQuery event to be placed here(focus,change,mouseenter)', 'class/ID to be Placed here', function (e) {       
    // jQuery events 
});

This will allow me to append to the DOM loaded by my page on the background. However this has a lot of issues as well. How do I append a jQuery plug in called Chosen to a dropdownlist which is sitting inside my partial view.

I have experimented by putting the jQuery inside the Ajax Options and using the Onsuccess property but this seems to have problems as well.

 <li class="PriceModal">
                        @Ajax.ImageActionLink("/InternalDB/Content/downloadCSV.png", "Pareto", "35px", "35px", "PartialViewPriceCalculator",
                        "PriceCalculator", new {@Pareto = "active" }, new AjaxOptions
                        { UpdateTargetId = "PriceCalculator", InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnSuccess = "$('.chosen2').chosen({ allow_single_deselect : true })"}, new { @style = "padding-top:30px" })
  </li>  

Is there a general approach to loading all of the needed jQuery inside a popup partial view or i just need to find hacks for each specific situation?


回答1:


You can just use the document.ready event to execute JavaScript when your PartialView finishes loading:

<div id="partialViewHere">
</div>

<script type="application/javascript">
    $(function() {
        // load whatever you need here
    };
</script>

I use this on an application to add events to buttons loaded through different PartialViews and it works perfectly.



来源:https://stackoverflow.com/questions/47549939/loading-jquery-in-partial-view-on-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!