I have a ASP .Net MVC4 Web application. In it I have my usual html for the _Layout.cshtml, which in turn loads the default Home/Index. All works fine.
In my index I am also loading a partial view. This works fine too. No probs.
I am using a the UI tools from the following site:
http://www.keenthemes.com/preview/index.php?theme=metronic
The problem is it seems to be primarily HTML4 and not designed for MVC out of the box so I am having to tweak it slightly to get it to work the way I want. (Nothing beyond anything very basic). For example, moving one part out to the index and using Renderbody() to load it so the actual html structure never changes. I have done this a million times to be sure I am not missing any closing tags or anything else that could cause my problem.
Up to this point there is no problem at all. Everything loads as it should.
I continued to create a 2nd View and its partial to extract other parts of the site. As usual, baby steps first. Before extracting any other code, I just used a little "Hello World" in the first page, and a similar string in the partial to be sure it was working. It was.
Now when I type in the url Home/ActionName the whole thing reloads as it should but looks horrible. and I get this error message:
0x800a1391 - JavaScript runtime error: 'jQuery' is undefined
Below is my code which clearly defines it:
<!-- BEGIN CORE PLUGINS -->
<script src="assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function ()
{
App.init(); // initlayout and core plugins
_Layout.init();
_Layout.initJQVMAP(); // init index page's custom scripts
_Layout.initCalendar(); // init index page's custom scripts
_Layout.initCharts(); // init index page's custom scripts
_Layout.initChat();
_Layout.initDashboardDaterange(); //Red date range
_Layout.initIntro(); //Pop up messages
});
</script>
It points me to the jQuery(document).ready part when I see the message.
Again, when I load the page normally, it works fine. When I type Home on its own it works fine. Its only when I type Home/AnythingElse that it gives this error message. Even if I type Home/ which should load in the Index file, it gives me this error message.
jQuery is defined, so why is this happening on postback?
Any help is appreciated.
Try setting the src for jQuery to be absolute from the site root:
<script src="/assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
Note the / before assets - when your src path does not start with a / the browser will try and load the asset relative to the current path, so in your example when you add the trailing slash to Home it will try to load jQuery from Home/assets/plugins/...
For me, the MVC bundlers were causing problems (in my case the ui bundler)
Here is the order which worked for me.
<script src="/Scripts/modernizr-2.5.3.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/bundles/jquery-ui"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
You need to add the jquery-x.xx.x.js first before the validate.js like this
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
Related
I am trying to use an MVC Partial to render a JavaScript grid. To do so, I have to load & utilize jQuery. However, I keep getting the following error:
$ is not defined
This should be simple...but apparently...it isn't.
THE PARTIAL LOOKS LIKE:
<h2>Inside the Partial</h2>
<div id="grid"></div>
<script type="text/javascript" defer>
// ERROR: $ is not defined
$(document).ready(function () {
// Awesome JavaScript Grid Stuff Will Go Here
});
</script>
THE VIEW LOOKS LIKE:
#using Web.Areas.Administration.ViewModels
#model LookupsViewModel
<h1>View Title</h1>
#Html.Partial(Model.PartialPath, Model.PartialModel)
Here are two main things that will help you solve your problem.
Make sure that your reference of the jQuery files is correct. Most you could had problem in the path.
Don't ever put JavaScripts in the partial views. Put those in parent view before the partial view where it has been called.
If you're loading jquery through script after the Partial view, you will be trying to run jquery variables before they are loaded and defined. Ensure that any jquery that you run (whether inline or not) is run after the page has requested and loaded jquery itself.
See: Can you write jQuery code inline before loading jQuery?
I'll give a bit more reason why you shouldn't put javascript in your partial views. If you use the Partial more than once, you risk having repeated javascript. That could mean variables are redefined, eventlisteners are added more than once, etc. causing some confusing bugs.
I'll cut right to the chase.
After I call RedirectToAction to any of my Action-methods, my JQuery libraries are not loaded until after the page has rendered. (Note: a direct route to the Action Method loads the libraries correctly). I'm not using renderSection for my scripts at the moment, but load the bundles in the header, in the _Layout.cshtml document:
<head>
#Scripts.Render("~/bundles/jquery")
</head>
This goes for all the libraries I try to load in the header, by the way.
I do see any reason why it wouldn't work when I'm redirection. Maybe I don't understand the RedirectToAction method correctly, in which case I would be very happy with an explanation.
An example of the redirect I use, from my controllers:
return RedirectToAction("Confirmation", new{orderId = order.Id});
(Keep in mind, that this problem persists trough all my controllers, and all actions)
Thanks a lot.
I found the error, after studying my Network tab in firebug. Here was the problem:
On redirects after form-posts, I load a jquery script via TempData. I accidentally made an external reference to jquery in that partial view's script.
Controller:
TempData["Message"] = new GenericMessage()
{
Message = "You need to select a date",
MessageType = GenericMessages.danger
};
return RedirectToAction("Index", "Home");
Partial View Script:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript"> $(function () { $('div.alert-generic').delay(3500).fadeOut(); }); </script>
<div class="alert alert-block alert-#genericMessage.MessageType.ToString() alert-generic">
×
#Html.Raw(genericMessage.Message)
</div>
This caused JQuery to be loaded twice (in different versions), on redirects.
After I removed the reference from the script, it all worked perfectly again. Thanks to those of you who tried to help me out, and I apologise for not seeing this error my self, before now.
I have done lots of reading up but I don’t understand why this is not working. I am using VS2010 with current updates. I want to Load a Web Page into the C# Web Browser Control (This Application is a Windows Forms Application):
this.webBrowser1.Navigate("https://mydomain/L1/L2/L3/L4/webpage.asp");
this.webBrowser1.PerformLayout();
In my understanding, to call Javascript Functions from C#, one would use:
this.webBrowser1.Document.InvokeScript("passwordReset");
or if one had Parameters to pass:
object[] parameters = new object[3];
parameters[0] = “1”;
parameters[0] = false;
parameters[0] = “3”;
webBrowser1.Document.InvokeScript("passwordReset", parameters);
My Web Page code is as follows. I have shown both methods I have tried. One seems to work, if I insert the Javascript into the page.
I don’t want to work with this method due to limitations I have. I need to be able to call the *.js File as shown:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My Test Page...</title>
<script type="text/javascript" language="javaScript">
function passwordReset()
{
alert("You're about to change your password!!");
}
</script>
<script type="text/javascript" src="/L1/L2/Password_Reset.js"></script>
</head>
Please note, I am not including both Javascripts in my page at the same time. I have only included both in this example.
Can someone please explain why this method, when calling on functions in the “Password_Reset.js” file, is not working as desired?
I have tried setting full permissions: [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
and also making this app Com Visible: [System.Runtime.InteropServices.ComVisibleAttribute(true)]
EDIT: What I am trying to achieve, is to be able to run Javascripts after webBrowser1.Navigate("URL"); when they are written into the page code as Follows:
<script type="text/javascript" src="/L1/L2/Password_Reset.js"></script>
EDIT: In Re-Reading my question, I wonder if this issue is a Folder Level problem and the Script is not loading? Can someone advise on this?
The solution was, in the end, very simple, and a little on the obvious side. I am a little embarrased.
Once the Browser Control Document Completed:
webBrowser1.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(webBrowserTest_DocumentCompleted);
Event has been called, and when:
webBrowser1.PerformLayout();
has been run, the Javascripts, at this stage has not fully loaded from what I can see. If I set a delay timer up and count a 1000 milliseconds then call my Javascript, the whole thing works perfectly. This is unless, by delaying the calls to my javascript, are in-turn allowing another issue in the background to resolve itself?
I guess the next thing to solve, is why is the DocumentCompleted eventhandler not including the loading of scripts in the way one would expect.
I hope others find this usefull and it saves them the time I spend resolving ths issue.
I'm not sure of what you are trying to accomplish.
However, I suggest you to look at startup script registration methods. If you use them, a JavaScript function will be executed in client browser after html document loading.
Take a look at this article. Maybe you can use it solve your problem.
I have a JavaScript code which links to survey poll page. When I am embedding the JavaScript code in normal aspx page (without master page), I am getting the survey normally without any issues, but when I am embedding the same code in page which uses master page, I am getting blank page.
This way doesn't work: http://gyazo.com/27f38b5b04897cf0b17747eab05cf746
This way works: http://gyazo.com/c69d3b95afe4a0070cd09834e479a97f
Update
Using <script src='<%=ResolveClientUrl("~/Survey/xlaabsolute.asp?p=1")%>' type="text/javascript" /> renders the poll correctly but the button for voting doesn't do any postback http://gyazo.com/b39fcaa8de3438c8c2a625e3816ba4be.
I can see the content http://gyazo.com/b39fcaa8de3438c8c2a625e3816ba4be
Chances are it's how the script is referenced.
You're using a relative position in your src attribute which could potentially change if it's not in a location that allows Survery/... to be found. Maybe change it to /Survey/... so it always locates the file based on the root path and not where the document currently resides?
You can also make your script tag runat="Server" and reference the script using traditional ASP relative links: src="~/Survey/..." so it resolves correctly.
The way to resolve the issue and make it work regardless of where the control is being used is to use ResolveClientUrl as so:
<script src='<%=ResolveClientUrl("~/Survey/your_script.js")%>' type="text/javascript" />
I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}