How to use jquery in ASP.​NET Core - c#

I created a ASP.NET core template and wrote a jquery script. When I look at the page I see that jquery is loaded into the page, but the script doesn’t run. I looked at the ASP.NET docs page and my layout.cshtml looks the same, so are there extra steps I must take to get jquery working?
Home page
#{
ViewData["Title"] = "Home Page";
}
<!-- Page Content-->
<div class="container">
<div class="row">
<form method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files" multiple />
<input type="button" id="upload" value="Upload Selected Files" />
</form>
</div>
</div>
<script>
$(document).ready(function () {
alert("Test");
});
</script>
Solution
#section scripts
{
<script>
$(document).ready(function() {
alert("Test");
});
</script>
}

I suspect your jquery is loaded after the rest of the page content.
This means that you cannot reference jquery objects as the library has not been initialised yet.
Move the page script after jquery has loaded.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(document).ready(function () {
alert("Test");
});
</script>
For efficiency I recommend you do this in one of two ways:
OPTION 1
Use a master script file that loads after jquery.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/master.js"></script>
OPTION 2
Use a placeholder template that will always load after jquery but can be initialised on individual pages.
Master _Layout Page
<script src="~/lib/jquery/dist/jquery.js""></script>
#RenderSection("Scripts", required: false)
Content Page
#section Scripts {
<script>
$(function () {
alert("Test");
});
</script>
}

FOR CLARIFICATION
If you are referencing jQuery in your _Layout page.. double check to ensure that that reference is at the TOP of your _Layout page because if it is at the bottom, then every other page you have that use the _Layout and has jQuery, it will give you errors such as:
$ is undefined
because you are trying to use jQuery before it is ever defined!
Also, if your are referencing jQuery in your _Layout page then you do not need to reference it again in your pages that use your _Layout style
Make sure that you are loading the reference to jQuery before you start using <scripts>.
Your cshtml should work if you put the reference above your script as so:
<script src="~/Scripts/jquery-1.10.2.js"></script> // or whatever version you are using
// you do not need to use this reference if you are already referencing jQuery in your Layout page
<script>
$(document).ready(function () {
alert("Test");
});
</script>

If you create a new .Net Core 2.2 - Web Application with Razor Pages and try to add a jQuery script in index.cshtml you will get the error Uncaught ReferenceError: $ is not defined. As already mentioned this is because jQuery is loaded after the rest of the page content.
Fix this by navigating to Pages\Shared\_Layout.cshtml and add the scripts section to the html head tag instead. Then it will work:
Example:
Move from below </footer>:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
</script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
Into <head>, should look like this:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - JiraApp.Clients.Web</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
</environment>
<link rel="stylesheet" href="~/css/site.css" />
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
</script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</head>

Thanks to everyone who contributed to these answers. I am new to JavaScript/jQuery and have been trying to get jQuery scripts to work for over two weeks now. I have gotten a few examples to work but, until now, I had no idea why something worked or did not work.
All of the examples I have looked at online show the references to .js files at the bottom of the page. None of the examples explain how the _Layout.cshtml file works in relation to the Razor views in an application. It is so confusing to add the links and script references to the _Layout.cshtml file only to have it not work as expected. Next, I moved the links and references to a header section on the razor page and it still did not work. Now that I have everything organized correctly, it is working and I understand why!!!
The key was putting the script inside the #section Scripts {} block. I had seen the call to RenderSectionAsync but did not realize what it was doing. This is how the bottom of my _Layout.cshtml file looks now:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery/dist/jquery.inputmask.min.js"></script>
<script src="~/lib/jquery/dist/inputmask.binding.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#await RenderSectionAsync("Scripts", required: false)
I hope many new developers see this post. When it comes to an ASP Net Core application with Razor views, the information provided in this thread is priceless! Again, many thanks to everyone who contributed to the answer.

must write below first line in while where you want to execute script.
if you write first line in other wile, it is not working.
below example to test JQUERY work or not.
<script>
$(document).ready(function () {
alert("Test");
});
</script>

This is similar to the fullcalendar question posed here on Stackoverflow. I shared the following solution on that question --
This is a good reference for what has been asked here. I downloaded jQuery directly and unarchived it into the wwwroot/lib folder/directory to get going with my project - however as I needed more JS libraries, it seemed that the Nuget option of installing JS libraries into my project really was an impossible path/option.
Consider;
not sure why you would use nuget packages for javascript libraries. your example has not been updated in the last four years, and probably doesn't support .net core projects (may not even work a current version of jQuery).
you should be using a javascript repository and package mangers like bower or npm, that manages the dependencies between libraries.
That is from the linked MS Forum. Anyhow, the question can be flagged as a duplicate of the other Fullcalendar question (which was posed two years prior to this one).

Related

Razor Pages Asp.Net-Core install FullCalendar

I am trying to install FullCalendar library to use in my Asp.Net Core Web App with Razor Pages and I installed the Nugget Package jQuery.FullCalendar.
In my Index.cshtml I use:
<div id="calendar"></div>
And in my site.js file I use:
$(function () {
$('#calendar').fullCalendar({
})
});
But when I run the app nothing happens. Did I missed some steps or this library is not working for Asp.Net Core?
For FullCalendar is a client-side library,I suggest that you could use LibMan.Refer to:
How to use LibMan.
Search for the js library:
1.moment.js:
2.FullCalendar.js:
Then your razor pages should like below:
<div id="calendar"></div>
#section Scripts
{
<link href="~/lib/fullcalendar/fullcalendar.min.css" rel='stylesheet' />
<script src="~/lib/moment.js/moment.min.js" ></script>
<script src="~/lib/fullcalendar/fullcalendar.min.js"></script>
<script>
$(function () {
$('#calendar').fullCalendar({});
})
</script>
}
Be sure your _Layout.cshtml is like below:
<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>
Note:If you do not apply _Layout to the razor pages,be sure add the jquery.js firstly then add moment.js and fullcalendar.js.The order could not change.
Another way is that you could use cdnjs without installing the js library:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script>
Result:

Create a partial view for the imports of css and js asp.net core 2.2

It is a question regarding design. In my ASP.Net Core MVC app I have 2 Layouts. My Default Layout and my Admin Layout which are quite self explanatory by there name. I do import the same js and css for both of my layouts e.g. Bootstrap and jQuery and some more. I wonder if I should create a partial view which contains these.
There might be different solutions which I do not know about.
Any help is appreciated.
You can use nested layouts to have a hierarchy of layouts. I have a similar scenario as yours. I have a _MasterLayout.cshtml in Shared with the full set of CSS and JS I pull in for all pages. Then create a separate layout file for different sections. Reference the master layout at the top and then include all of the other sections adding specific code for that layout.
So you could have a MasterLayout like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="content-security-policy" content="upgrade-insecure-requests" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
#RenderSection("Styles", required: false)
<title>#ViewData["Title"]</title>
</head>
<body>
<div class="container body-content">
#RenderBody()
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
And a separate nested layout like the following:
#{
Layout = "_MasterLayout";
}
#RenderSection("Styles", required: false)
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
// custom navbar for anonymous users
</nav>
<div class="container body-content">
#RenderBody()
</div>
#section Scripts {
#RenderSection("Scripts", required: false)
}
There's not a lot of documentation for nested layouts. Here's one other article I found describing the approach.
I can't tell if it would be good or not to create a partial for both layouts, but I would recommend a hidden, tiny tag helper for script tag (and link as well) that I think you might find useful. It is asp-src-include.
<script asp-src-include="/assets/js/*.js"></script>
is rendered to the html like;
<script src="/assets/js/jquery.js"></script>
<script src="/assets/js/bootstrap.js"></script>
<script src="/assets/js/custom.js"></script>
and same functionality applies to link tag as well.
I think this might tidy up your layouts a bit. Yo can find out detailed posts about these tag helpers here and here

How to decrease page load time (combine javascript)?

Page created using ASP .NET MVC 2 takes 1.7 sec to load.
It contains 13 js files as shown below. Firebug shows that every js file load returns 304 response but since there are 13 files it may increace page load time a lot.
Chrome audit red alert recomments to combine js files.
How to combine them to single file using ASP.NET MVC 2 automatically or other way to decrease load time ?
There should be separate js files in project to allow to replace them but those should delivered
as single js file probably.
jqgrid, jquery, jquery-ui, tinymce and some jquery plugin js files are used as shown below.
Visual Web Developer Express 2010 is used. Application is running under Mono 2.10/Apache and under Windows/IIS
site.master contains:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1" />
<link rel="stylesheet" href="../../themes/redmond/jquery-ui-1.8.12.custom.css" type="text/css" />
<link href="../../Scripts/jqgrid/css/ui.jqgrid.css" rel="stylesheet" />
<link href="../../Content/Css/Site.css" rel="stylesheet" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
</title>
<script type="text/javascript">
"use strict";
var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>
<script src="<%= Url.Content("~/Scripts/jquery/jquery-1.7.1.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery-ui-git.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/i18n/jquery.ui.datepicker-et.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.contextmenu-fixed2.js")%>" type="text/javascript"></script>
<% if (CurUser.GetLanguage() == "EST")
{ %>
<script src="<%= Url.Content("~/Scripts/jqgrid/js/i18n/grid.locale-et.js")%>" type="text/javascript"></script>
<% }
else
{ %>
<script src="<%= Url.Content("~/Scripts/jqgrid/js/i18n/grid.locale-en.js")%>" type="text/javascript"></script>
<% } %>
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqgrid/jquery.jqGrid.src-multiselect1-deleteandsortpatches.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqgrid/jQuery.jqGrid.dynamicLink.js")%>"></script>
<script src="<%= Url.Content("~/Scripts/json2.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.form.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/TinyMCE/tiny_mce_src.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/TinyMCE/jquery.tinymce.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/myscripts.js")%>" type="text/javascript"></script>
<script type="text/javascript">
var
$grid;
$(function() {
"use strict";
<% if (TempData["Message"]!=null) {
setTimeout( function() {
showMessage ( '<%= TempData["Message"] as string %>');
...
Update
I tried Oleg suggestion in answer but got error jQuery is not defined as shown in image below. How to fix this ?
IE console does not show any error.
I want suggest you to make one experiment using the Closure Compiler.
First of all you can try to concatenate all the JavaScript and all inline JavaScript code which you use on the page. You should hold the order of files of cause. It seems to me you will have two version of the results: one with CurUser.GetLanguage() === "EST" and another with CurUser.GetLanguage() !== "EST".
After you will have one JavaScript file you can use the Closure Compiler with a compilation_level of ADVANCED_OPTIMIZATIONS (see here) which can remove all unused JavaScript code. As the result you will get subset of jQuery, jQuery UI and other libraries which you really use on the page. The resulting JavaScript code will be other as on another pages, but it could be very small and could be better optimized as any separate files.
I recommend use head.js.
It really helps you to decrease page load time with using separate .js files. You just include one file with something like that:
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {
// all done
});
http://combres.codeplex.com/ allows you to keep separate javascript files and to combine and minify at runtime.
Works a real treat.
Looks like they've rolled something similar into asp.net 4.5:
http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
To overcome these type of situation you have many techniques. Some of are :
Page Specific JS : Try to add javascript files according to the requirement. Do not add any unnecessary JS which are not used in page.
GZIP Compression : Apply GZIP compression on pages and static js and css files.
Caching : At the server level (IIS) you caching can be applied on these static files like JS or CSS
http://sixrevisions.com/web-development/decrease-webpage-load-times/
Combine multiple JavaScript files into one JS file
Good Luck !!
Bundling Files Together
Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser
Bundling can significantly improve your first page hit download time.
Bundling reduces the number of individual HTTP requests to server by combining multiple CSS files and Javascript files into single CSS file and javascript file.
This site here has a good tutorial on how to add bundling to your application in five easy steps: http://websitespeedoptimizations.com/Bundling.aspx

Jquery UI in asp.net

How do i include jquery ui to be used in my system? I've already put the code in my header:
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
And how can I include the date picker which I already downloaded from jqueryUI. Here is the code of the date picker :
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<div class="demo"><p>Date: <input type="text" id="datepicker"></p></div>
I got confused how to export the downloaded file to asp. Thank you.
Did you also include the references to JQuery?
<link type="text/css" href="css/themename/jquery-ui-1.8.23.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.23.custom.min.js"></script>
See: JQuery UI Documentation

Datepicker displayed incorrectly

I am trying to write an MVC.NET web-site and I want to use the datepicker component from jQuery. To use jQuery I am using the following code on my Layout page:
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.7.2.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.core.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/jquery.ui.all.css")" type="text/css" />
<link href="#Url.Content("~/Content/jquery.ui.datepicker.css")" type="text/css" />
</head>
On the page where I want to use datepicker I use the following code:
<script type="text/javascript">
$(document).ready(function () {
$("#FromDate").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>
...
<div class="editor-field-search">
<label for="fromDate">From date:</label>
<input type="text" id="FromDate" name="FromDate" value=""/>
</div>
But datepicker is displayed in a weird way:
I've Googled and tried to fixed, but have not find a way to fix my problem. What am I doing wrong?
It's a pure CSS reference problem. You don't have the CSS referenced correctly. Run my sample Using the HTML5 and jQuery UI Datepicker Popup Calendar with ASP.NET MVC and use the F12 tools and compare with your code to figure out why your CSS is not being used. – Rick.Anderson-at-Microsoft.com
comment out my CSS reference and you get the same malformed calendar. The F12 tools are great for figuring this out.
if you are copy paste your source code here I think you are missing a ">"
<label for="fromDate">From date:</label**>**
<input type="text" id="FromDate" name="FromDate" value=""/>
Does it work if you close the label tag?
<label for="fromDate">From date:</label>
^
I'm assuming you have downloaded a theme from jQuery's ThemeRoller...could try a couple things:
Use the jQuery and jQuery UI Javascript versions included in the download to
make sure it is compatible (in js directory of download). Looks
like jQuery 1.7.1 is the latest version included in jQuery UI
download and you have jQuery 1.7.2 on your page.
Try the jQuery UI css file in the css\custom-theme directory - it includes all the css needed for all the jQuery components. Also
check to make sure the images were copied next to the jQuery css
file in your application like it is in the custom-theme directory.
jQuery Getting Started Guide

Categories

Resources