How do I add my own JS to a Razor view? - javascript

I want to include lines 4-6 in the Scripts section of the page. The code below is in my view. Instead of being written to it prints to the page. I can't figure out what I'm doing wrong. Somehow it seems this is a very uncommon thing to do as I am not finding examples of how to do it correctly.
1 #section Scripts {
2 #Scripts.Render("~/bundles/jqueryval")
3 #Scripts.Render("~/bundles/datetimepicker")
4 $(function() {
5 $(".datetimepicker").datetimepicker();
6 });
7 }

keep it inside the script tag
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script type="text/javascript">
$(function() {
$(".datetimepicker").datetimepicker();
});
</script>

You script needs to be in a <script> tag
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script type="text/javascript">
$(function() {
$(".datetimepicker").datetimepicker();
});
</script>
}

If your view uses the _Layout.cshtml page then you can add a custom section like this at your _Layout.cshtml page:
#RenderSection("scripts", required: false)
If you want all you page should require this section then set require:true
In your view you code should look like this:
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script>
$(function() {
$(".datetimepicker").datetimepicker();
});
</script>
}

Just add a script tag and put this code inside the script tag
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script type="text/javascript">
$(document).ready(function () {
$(function() {
$(".datetimepicker").datetimepicker();
});
});
</script>
}
But There might be a problem because sometimes the asp does not render the scripts . Also you do need to render the scripts in the partial views in case.

Related

jQuery only seems to be working in Layout.cshtml

I am currently working on the basics of a .NET C# Razor page application running the following:
Razor pages
.NET 5/C#
jQuery v3.5.1
Bootstrap v4.3.1
My current issue is that jQuery (and plain JS) are only working in the Layout.cshtml file, I have tried the following:
Script tags in the head of _layout.cshtml
Script tags at the bottom of the body of _layout.cshtml
Wrapping the jQuery in #section scripts{}
At this stage I am fairly sure it is just a case of, it needs to be setup in a very particular way in .NET5, but I really have no more clues
Bottom of _Layout.cshtml
</header>
<div class="container-fluid">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Head", required: false);
#RenderSection("Scripts", required: false);
</body>
</html>
Bottom of the index.cshtml file
#section scripts {
<script>
$(document).ready(function () {
$(".btn-reply").click(function (event) {
alert("it works");
});
});
</script>
}
Rather frustratingly this turned out not to be anything JS related at all, in actually fact this was down to main div with the class of row having a z-index of -1, no idea how this came to be, I don’t recal having set this, but if I did I whole apologise to anyone who took the time to read this.

How to import a js file into view in mvc

I have below view with scripts at the end:
View:
(...)
// here my html items etc...
(...)
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// here all my stuff
function sample1()
{
}
function sample2()
{
}
function sample3()
{
}
</script>
so what I want is to put all the code within into a js file and place it under /Scripts folder in mvc 4 so how to do this? In this script I refer to items in the view.
so after this change I have:
View:
(...)
// here my html items etc...
(...)
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js)"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/Customs/MyCustomJsFile.js")">
</script>
Javascript file (under /Scripts folder):
MyCustomJsFile.js:
function sample1()
{
}
function sample2()
{
}
function sample3()
{
}
in runtime I am getting an error saying synatx error in MyCustomJsFile.js in the ie debug console so I click the error and first line is shown as error:
but my js file has not any script line....
The only thing that should be in your MyCustomScript.js file is the code you had between the <script> tags, not the tags themselves nor the <script> tag to include jQuery. jQuery should be included in your view on in your Layout and it should be included before your file.
For example, your view:
<script type="text/javascript" src='#Url.Content("~/Scripts/jquery-1.10.2.min.js")'></script>
<script type="text/javascript" src='#Url.Content("~/Scripts/Tests/MyCustomScript.js")'></script>
Your MyCustomScript.js file:
// here all my stuff
jQuery should really be included on your Layout since you will likely be using it on most, if not all, of your Views.

Is there a way to append code to an asp.mvc section

I have partials that get rendered as part of a complex page composition.
Some of these partials need some jQuery OnDocumentReady goodness to seed list data etc.
There can be many of these partials chosen during a render (it's very dynamic)
in my _Layout I have a section definition that looks like this
<script src="http://my/fav/cdn/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($) {
#RenderSection("OnDocumentReadySection", false)
});
</script>
in my partials I want to write something like this
#section OnDocumentReadySection{
$('#partial-1').init();
}
and have the result of the page render end up with something like this
<script src="http://my/fav/cdn/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($) {
$('#partial-1').init();
$('#partial-2').init();
$('#partial-3').init();
$('#partial-n').init();
});
</script>
This is to make sure all my javascript is at the bottom of the rendered html which I am told is far more optimal.
Instead of:
jQuery(function($) {
$('#partial-1').init();
$('#partial-2').init();
$('#partial-3').init();
$('#partial-n').init();
});
You should instead assign each of them a common css class (even if you don't define a definition for it) and then do this in the head:
jQuery(function($) {
$('.classname').init();
});
Or if need be:
jQuery(function($) {
$('.classname').each(function(){ $(this).init(); });
});

Razor RenderSection within script tags - How to insert script from view into template function

I'm using MVC 3 with the Razor view engine and I would like to inject scripts from multiple views into one centrally defined $(document).ready(); function in the master page.
I have tried the following:
<script type="text/javascript">
$(document).ready(function () {
//OnLoad Script load area
'#RenderSection("DocumentReady", false)'
});
</script>
In my master view, and then:
#section DocumentReady{
alert('Document is ready!');
}
In my view, but unsuprisingly, we get compilation errors due to the javascript not being within a <script> tag.
If there are a lot of small view controls that need to run some initialisation script in the $(document).ready() function, it would be nice to keep them all together in a single place.
Is there a way to inject javascript to a master view without the surrounding <script> tags and without affecting compilation?
You don't need the single quotes around the RenderSection call in your layout:
<script type="text/javascript">
$(document).ready(function () {
#RenderSection("DocumentReady", false)
});
</script>
and inside the view:
#section DocumentReady {
alert('');
}
But it will probably be more readable if you have a scripts section in your layout:
#RenderSection("Scripts", false)
and inside the view:
#section Scripts {
<script type="text/javascript">
$(function() {
alert('');
});
</script>
}
For example, in your _layout.cshtml :
#RenderSection("JavaScript", required: false)
And then in your view :
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="#Url.Content("/Scripts/AnotherScript.js")"></script>
<script type="text/javascript">console.log("in the js");</script>
}
Hope that helps

JavaScript function stops working when it is moved to an external .js file

I moved a function from an html page to an included reference file. It stopped working.
The complete contents of the file are:
alert('file included');
function doAlert() {
alert('functions work');
}
In the html page, I have
<html>
<head><title>Page</title></head>
<body>
HTML Template Header
Some Content
ASP.NET MVC Partial View Starts
<script type="text/javascript">
doAlert();
</script>
ASP.NET MVC Partial View ends
HTML Template Footer
<script type="text/javascript" src="/Scripts/wtf.js"></script>
</body>
</html>
The 'file included' alert works, but the 'functions work' does not. What am I doing wrong?
Make sure you include the file before you execute the function.
<script src="file.js" type="text/javascript"></script>
<script type="text/javascript">
doAlert();
</script>
you should call your function(s) in the following way:
window.onload = function() {
doAlert();
// func_1();
// func_2();
// func_3();
// ...
// func_n();
};
See this for more information about the window.onload event.
Code example on jsFiddle

Categories