Kemal Tezer Dilsiz Kemal Tezer Dilsiz - 3 months ago 13
Javascript Question

How to use loadjsfile in .NET Core in a View class?

I have the following code that I have migrated from .NET to .NET Core.

Unfortunately, the javascript files are not being loaded with the loadjsfile. What can I use to be able to load these javascript files into my View Class?

<script>
function loadjsfile(filename) {
var fileref = document.createElement("script");
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filename);
document.writeln(fileref.outerHTML);
};
if (jQuery == undefined) loadjsfile(@Url.Content("~/Scripts/jquery-1.11.2.min.js"));

loadjsfile(@Url.Content("~/Scripts/jquery.validate.min.js"));
loadjsfile(@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js"));
loadjsfile(@Url.Content("~/Scripts/contactusform.js");

</script>


Currently, I know for sure that "contactusform.js" is not being loaded because I call a javascript method in one of the input buttons and it says that the method cannot be found.

Answer

If loadjsfile method take a string value, you should wrap the result of your Url.Content call in quotes.

loadjsfile("@Url.Content("~/Scripts/jquery.validate.min.js")");

You may also consider using the script tag helper with asp-fallback-src attribute.

<environment names="Staging,Production">
    <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery">
    </script> 
</environment>

Update the asp-fallback-src value to your local copy of the library.