3

I have a layout and a view and a partial view. I used my layout in view and in view I load partial view with ajax into view. I used @RenderSection("Script", required: false) in my layout for loading my validation js file into partial view with this statement:

@section Script{
    <script src="~/Content/js/register.js"></script>
}

but after running my project and get view source I saw that file still doesn't load to this page.Then I put @section Script{ <script src="~/Content/js/register.js"></script> } in my View in this way file loaded but any of validation don't run. But when I copy script file code into partial view they are running. Now I want know why when I used file don't run my scripts?

Thanks!

Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47

3 Answers3

4

You can refer following code to render your script:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

In your case you have to use this function like this:

After your success request:

$('#divreg').html(data);
loadScript("~/Content/js/register.js", function(){
    //initialization code
});

Hopefully it resolves your issue.

Thanks

Happy coding :)

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
  • Seriously, all that code just because the code in the script does use event delegation? –  Aug 03 '16 at 07:49
0

you can not use @section Scripts{} in your partial View. It changes nothing and does not render. you'd better use the script file without Section Helper.

Read more: Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Community
  • 1
  • 1
MRebati
  • 591
  • 14
  • 29
0

To provide an update to this question, this is currently how we do this internally in Razor partials:

  • Button click is fired, partial is rendered in parent view
  • The partial view has it's own segment of js inside either a file with a script src=".. tag or locally inside <script> tags
  • Similar to document.ready, an IFFE is used to immediately invoke a series of events to load JS widgets etc held within the partial.
  • Partial view loads JS correctly.

An example IFFE for this would be:

<script>
    function ShoutAtMe(str) {

        alert(str)

    }

    (_ => {
        ShoutAtMe("HELLO")
    })();
</script>

This script block would be within the Partial.

James Gould
  • 4,492
  • 2
  • 27
  • 50