$ is not defined in view - c#

I'm working on ASP.NET MVC 5. I have a viewstart.cshtml and imported the reference for my jquery like this
<!-- jQuery and Bootstrap JS-->
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script src="~/Scripts/Bootstrap/js/bootstrap.min.js"></script>
In my view for HomeController I have alert function on document ready but there is an error that says $ is not defined.
But when I import the jquery directly to the view of my HomeController, it works fine. Why is that? The view of my HomeController is actually using the viewstart.cshtml that has the reference for jquery. Am I doing the correct way to import all my js/css files in Layout.cshtml? thanks for any help
In my View for HomeController if I reference the jquery directly, there is no error and it's working fine. But I want to do it once so all of the views don't need to reference it.
see below code:
#{
ViewBag.Title = "Welcome";
}
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script>
$(function () {
alert("hello francis!")
})
</script>
<h2>WELCOME !!</h2>

It looks like you're loading your custom scripts before jquery.
Make sure you have something like this in Layout.cshtml (not _ViewStart.cshtml) somewhere between #RenderBody and </body>:
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
<script src="~/Scripts/Bootstrap/js/bootstrap.min.js"></script>
#RenderSection("scripts", required: false)
and in the view you have to include your scripts into scripts section like:
#section scripts {
<script>
//your custom scripts here
</script>
}
This will ensure you that jquery will be loaded before your scripts.
Anything placed into section in the view will not be rendered during view render in RenderBody, and will be rendered only in RenderSection.
So jquery is loaded first in layout file, and only then section from the view containing your custom scripts that uses jquery being rendered.

usually you should use bundling to get jquery working.
inside the App_Start folder there's a file called BundleConfig.cs. Place the required jquery libs inside your scripts folder and update the bundle config file as follows:
public static void RegisterBundles(BundleCollection bundles)
{
// The jQuery bundle
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
//"~/Scripts/jquery-1.9.1.*",
"~/Scripts/jquery.min.js"
//"~/Scripts/jquery-ui-1.10.2.custom.js"
));
bundles.IgnoreList.Clear();
bundles.IgnoreList.Ignore("*.intellisense.js");
bundles.IgnoreList.Ignore("*-vsdoc.js");
bundles.IgnoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
}
in your Layout.cshtml right in the <head> tag area place the following piece of code to render your bundles defined:
#Scripts.Render("~/bundles/jquery")
You should now be able to use jQuery as expected.

This line:
<script src="~/Scripts/jQuery/jQuery-2.1.4.min.js"></script>
runs on the client's end.
The tilde (~) is the way to get to the server's root directory.
You can use url's with a tilde(~) on you server (e.g. using Server.MapPath) but they shouldn't be used on the client's end.
You can either create a relative url or an absolute url on your client, but don't use the tilde (~).
Your error ($ is not defined) means that JQuery has not been loaded. Either:
You didn't load JQuery correctly - check you url (easy to with the dev tools).
You are using the JQuery before it was loaded.

Go to Views/Shared/_Layout.cshtml and move this piece of code:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
from the body tag to the head tag and that should look like this:
...
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")/
#RenderSection("scripts", required: false)
</head>
...
...For me personally that worked out fine, there is no more need to embed direct references to jquery in each html page.

Related

Issue getting started with FullCalendar in ASP.Net Core

For a reason or another, I really could not set up the FullCalendar.io for my ASP.Net Core project Razor Page. The documentation is also pretty poor imho so I will highly appreciate any tips on what I should do.
Firstly, I created the CalendarController.cs. The View that should show the calendar at this point is Index and I kept the controller method empty, like this:
public ActionResult Index()
{
return View();
}
The Index.cshtml is taken from here: https://fullcalendar.io/docs/initialize-globals
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<link href='fullcalendar/core/main.css' rel='stylesheet' />
<link href='fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='fullcalendar/core/main.js'></script>
<script src='fullcalendar/daygrid/main.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ]
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
If I run my project and go to Calendar/Index, the page is blank. What step did I miss? On the getting started page, they state that a package has to be installed. The way I did was Nu-Get Package Manager -> Install Jquery.FullCalendar - is this the wrong way? I tried running this npm install --save #fullcalendar/core #fullcalendar/daygrid in the Package Manager Console but it didn't work out.
Any help regarding this is highly welcomed, as I said. Sorry for posting such a thing with all the documentation out there! I just couldn't figure it out coming from them.
EDIT: I also get the following warnings in the console:
C:/Users/user/source/repos/Intersection/Intersection/Views/Calendar/fullcalendar/core/main.js' not found. and 'C:/Users/user/source/repos/Intersection/Intersection/Views/Calendar/fullcalendar/daygrid/main.js' not found.
I think your problem is here:
<link href='fullcalendar/core/main.css' rel='stylesheet' />
<link href='fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='fullcalendar/core/main.js'></script>
<script src='fullcalendar/daygrid/main.js'></script>
I dont know wheres located your view, but in this instruction you are telling to look for the scripts in the same level as you are, which probably it is wrong; because you will have on the wwwroot folder, so something like should work, thats why it is telling you: "Couldnt file that file" , becasue theres no file in that location:
<link href='~/fullcalendar/core/main.css' rel='stylesheet' />
<link href='/wwwroot/yourPaht/fullcalendar/daygrid/main.css' rel='stylesheet' />
<script src='~/wwwroot/yourPath/fullcalendar/core/main.js'></script>
<script src='/fullcalendar/daygrid/main.js'></script>
Try that 4 ways and let us know!!
Where did you put the JavaScript and CSS files for fullcalendar? Seems like it's looking for them underneath the views folder here:
/Views/Calendar/fullcalendar/daygrid/main.js
I'm guessing they are actually installed at the root of your project or under a /content or /scripts folder or something, so you'll need to update the script and link tags for your js and css files to point to the right place.
maybe you can try to download libary
put js file and css file to ~/content or ~/script

How to load specific script and css for a specific View? [duplicate]

This question already has answers here:
how to add script src inside a View when using Layout
(4 answers)
Closed 4 years ago.
Suppose I have a view called Login.cshtml, which I need to load these:
<link href="~/css/particle.css" rel="stylesheet" />
<script src="~/js/particle-js/particles.min.js"></script>
<script src="~/js/particle-js/app.js"></script>
In my application I have also _Layout.cshtml which contains the basic script to load for each, page. How can I load the script and css above in the when the user access to Login.cshtml view, as happen in _Layout.cshtml?
What I learned is the existence of #section, but I don't if is the best practive to do this, someone could suggest me how to do it properly?
Thanks in advance.
Section seems to be the appropriate solution for this use case.
So you will use the RenderSection method in your layout cshtml file. For example, if you want to include some static resources inside the head section of the document, you will create a new section in the head element of your layout
<head>
#RenderSection("PageCss",required:false)
</head>
<body>
<div>
#RenderBody()
#RenderSection("scripts", required: false)
</div>
</body>
and in your view(Login.cshtml), you will add the static resources through this specific section.
#section PageCss
{
<link href="~/css/particle.css" rel="stylesheet" />
<script src="~/js/particle-js/particles.min.js"></script>
<script src="~/js/particle-js/app.js"></script>
}
#section PageCss
{
<script src="~/js/anotherSciptWhichDoesNotBlockRendering.js"></script>
}
When razor executes the code, it will render the correct html.
You may create more than one section and use it as needed.
Consider using the async and defer attributes on script tag as appropriate to prevent render blocking script download/execution behavior.

Render section inside layout file

I try to understand how works sections in Razor views. I have 2 layout files: _Layout.cshtml and _LayoutChild.cshtml which use the first layout inside. I try to declare sections in _Layout.cshtml and render it in the same file. Markup not appears but when I declare section in _LayoutChild.cshtml everything works. See example below:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
#RenderSection("A", false)
</head>
<body>
#section A{
<script>
alert("I'm in Layout!");
</script>
}
</body>
</html>
_LayoutChild.cshtml
#{
Layout = "_Layout";
}
#section A{
<script>
alert("I'm in LayoutChild!");
</script>
}
I understand that declaring section in the same file looks strange but I would like to know why it don't work?
While developing web site or application. Every page have some common section like header, footer, sidebar etc. Write and maintain these on every page is a hard job. So, we need a way to put them in one single place. Luckily in MVC we have Layout concept for this. We put all the common code in it and changing content in Views which will render in layout where we call #RenderBody() method.
Why we need sections ?
Some time we wanted to show specific content on some specific pages like newletters only show on blogs and home page, top news or some advertising banners on specific pages. For these type of scenarios sections rescue us in MVC.
How we can use section ?
We need to follow these two steps to used sections in MVC.
Declare Section in Layout, give it a name and tell is it required on
every page or not.
Define it in view
When views render then section content also added where we declare the section.
Code Example
1. Most of the time we need some specific javascript code for view. So we can do it like this
_Layout.cshtml
#RenderSection("scripts", required: false)
view.cshtml
#section scripts{
<script>
alert("I'm in Layout!");
</script>
}
2. News Letter example
_Layout.cshtml
#RenderSection("newletter", required: false)
view.cshtml
#section newletter{
<h3> New Letter </h3>
... rest of the html ...
}

Ajax.ActionLink in MVC3 not working

I'm developing an Asp.net MVC3 website from VS2012RC. I'm trying to create a partial view to the website using Ajax Actionlink. But it is not working. After trying everything I know with my team and a lot of searching, I then tried it on a TestProject. To my further depression that is also not working. I have tried to work around this for a long time and now I'm calling SO.
This is how I created my test project. Please let me know whether I am making a mistake or this is a fault in my machine.
I have created an MVC3 empty Project with html5 semantic markup and with the view engine of Razor.
Then I added a Home controller to my project and created a view for View() action.
Then I created another action TestAjax().
Then I Created a partial view in the Home Folder in Views
Folder.
This is my Index view:
#{
ViewBag.Title = "Index";
}
<div>
#Ajax.ActionLink("This is a test ajax","testAjax",new AjaxOptions{ UpdateTargetId = "TestAjax" ,HttpMethod ="GET",InsertionMode =InsertionMode.InsertAfter})
</div>
<div id ="TestAjax">
</div>
Partial View is :
<h1>Testing testing testing testing</h1>
Now what I expect is that when I click the link the header hast to appear below the link in the TestAjax division. But what actually happens is in home page the link appears. When I click the link, it will go to the "/Home/testAjax" and display only the partial view. There is no partial view.
Can you tell me what is the wrong with this procedure.
EDIT:
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
<script src="#Url.Content(" ~/Scripts/jquery.unobtrusive-ajax.js")" type = "text/javascript"> </script>
</head>
When I check the resources in the webpage of the view Index():
This is a test ajax
Referenced the ~/Scripts/jquery.unobtrusive-ajax.js js file was not in my layout/view. Since I was not familiarized with ajax. So, people who are new to ajax in MVC and came here by Googling, First check this reference mentioned above is in your layout/view.

ASP.NET Dynamic JavaScript File

I'm writing a ASP.NET web application. It dosen't use Web Forms or MVC. It uses ASP.NET Routing to a Http Handler, and the handler just writes html to the HttpContext.
The final output of my html is something like this:
<html>
<head>
<title>...</title>
<script type="text/javascript">
...
</script>
</head>
<body>
...
</body>
</html>
Now, Instead of writing the (long) script into this page, I want to write it to another page, and then use the src of script element to reference it. The problem is, that the script is dynamic.
<html>
<head>
<title>...</title>
<script type="text/javascript" src="..."></script>
</head>
<body>
...
</body>
</html>
Any ideas?
Thanks.
Can't you just place the location of the dynamic script inside the src?
I.e., if http://www.example.com/foo is your HTTP handler, can you make another HTTP handler, http://www.example.com/bar for the dynamic javascript? You should be able to pass any parameters needed inside a query string.
your script is dynamic => I assume it changes based on the user/context/date/time ??
you should set your Response.Charset (to UTF-8) & Response.ContentType (to text/javascript)

Categories