1

I am creating an asp.net MVC application. I want to separate my js code from the razor code in view. So I've got a file with the path "~/Scripts/SearchProductsScript.js" _Layout.cshtml:

<head>
    ...
    <script src="@Url.Content("/Scripts/jquery-1.10.2.min.js")"></script>
    @if (IsSectionDefined("JavaScript"))
    {
        @RenderSection("JavaScript", required: false)
    }
  ...
</head>

_SomeView.cshtml:

@section JavaScript
{
    <script type="text/javascript" src="@Url.Content("~/Scripts/SearchProductsScript.js")"></script>
}

And SearchProductsScript.js:

var uri;

function test() {
    alert("TEST");
}

$(document).ready(function () {
    Doing something here
    $(':radio').change(function () {
        Doing something here
    });
});

I'm not sure how to properly use this separate js file. None of the functions is working and trying to call them from the _SomeView.cshtml doesn't work:

<script>
    $(document).ready(function () { test(); });
</script>

or

<input type="button" value="Search" onclick="test();" />
AOY
  • 355
  • 3
  • 22
  • 1
    Are you getting any errors in the development console in your browser, as you seem to have an extra `});` in your SearchProductsScript that has no business being there. May just be a mistake from where you've copied it to SO – George Mar 28 '17 at 10:05
  • oh I didn't remove it while deleting the code but this is not the issue – AOY Mar 28 '17 at 10:07
  • I get an error that the function is not defined – AOY Mar 28 '17 at 10:10
  • 1
    Check in console sources that your external javascript is loaded or not if not than it might be js path issue – Curiousdev Mar 28 '17 at 10:11
  • It seems to me that is is not loaded – AOY Mar 28 '17 at 10:26
  • when I added a string @Scripts.Render("~/Scripts/SearchProductsScript.js") to Layout.cshtml the script was called! – AOY Mar 28 '17 at 10:31

1 Answers1

1

So reason the js code was not called was that I was trying to set a section from the partial view which is not possible. RenderSection not working inside Partial View in ASP.NET MVC3

Community
  • 1
  • 1
AOY
  • 355
  • 3
  • 22