Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Section script not rendering in ASP.net MVC4 razor

I am developing a JQuery mobile application in ASP.net MVC4 razor using VSRC, In cshtml page section scripts are written like the following.

@section Scripts
 {
  <script type="text/javascript">
     $(document).ready(function () {
        jQuery("#register-form").validationEngine();
  });
 </script>
}

In layout.cshtml I have...

"@RenderSection("Scripts", false)".

It works for the initial page (page which render first), but when it linked via "ActionLink" to other pages then the section script written in those pages are not working.

Any ideas?

Please help, Thanks.

like image 954
Erma Isabel Avatar asked Oct 05 '12 06:10

Erma Isabel


2 Answers

I had the same problem. In order to workaround this I just avoid the "Scripts" section.

Remove @section Scripts{ from every page and put your js code at the end of the page.

For your example, make sure to move @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile") to the line before </head> in _Layout.cshtml. This will guarantee that jquery is loaded when it gets to $(document).ready(function () {...

===============================================

explanation about why it happens and other solution. http://lextell.com/blog/2012/10/23/script-section-is-not-rendered-in-asp-net-mvc-4-jquery-mobile-when-navigate-to-another-page-2/

like image 100
Erick B Avatar answered Oct 27 '22 11:10

Erick B


Following the line of Erick Bacallao, I'll sugest you the following:

Avoid using URL.Content() to load .min.js o .js files. Scripts.Render() choose the right file in every scenario (.js in Debug and .min.js in Release).

The modified _Layout.cshtml would look like this:

    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        $(document).bind("mobileinit", function () {
            $.mobile.ajaxEnabled = false;
        });
    </script>
    @Scripts.Render("~/bundles/jquerymobile")
    @RenderSection("scripts", required: false)

NOTE: Disabling jQuery MObile AJAX (like this does) is a patch... not a complete solution! UX decresases a lot.

like image 31
sesispla Avatar answered Oct 27 '22 11:10

sesispla