At the moment, I have added the jQuery source file to my ASP.NET project's Scripts folder. In the _Layout.cshtml page, I have included ~/Scripts/jquery-2.1.1.min.js. Right now, I can include jQuery code on every page I make this way:
If this page shows a popup I was succesfull.
<script>
$(document).ready(function(){
alert("works!");
});
</script>
However, I don't want to include a full script in every view. I would prefer to create a seperate JS file, put it in my Scripts folder, and then include it using Razor.
@{
//Razor Magic inserting Javascript method!
}
If this page shows a popup I was succesfull.
How do I do this? And is it the "correct" way to include a unique Javascript file for a single page?
Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.
The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.
JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.
$(function() { ValidatefuneralDate(); }); this will get invoked when the DOM is ready. $(document). on("pageload",function(){ ValidatefuneralDate(); });
You can put your page specific JS code in a separate JS file and can refer to your specific Views using the following piece of Code:
1) You need to put this section in your _Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-2.1.1.min.js)">
@RenderSection("JavaScript", required: false)
</head>
2) You need to add @section to the View in which you want to refer your JS file - (_ABCDView.cshtml)
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SampleScript2.js")"></script>
}
NOTE: @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will ignore the fact that there is no "JavaScript" section defined in your view. If true, the view won't render and an error will be thrown unless the "JavaScript" section has been defined.
And you are good to go!
Hope this will help you.
Thanks, Swati
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With