JQuery not loaded after RedirectToAction - c#

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.

Related

The following sections have been defined but have not been rendered for the layout page “~/Views/Shared/_Layout.cshtml”

I've this ActionResult:
[EncryptedActionParameter]
[CheckExternalUserRegisterSigned]
public ActionResult ExpedienteIIT(int idExpediente)
{
ExpedienteContainerVM model = this.GetExpedienteVMByIdExpediente(idExpediente);
return View("ExpedienteIIT", model);
}
ExpedientIIT View:
https://jsfiddle.net/pq16Lr4q/
_Layout.cshtml:
https://jsfiddle.net/1ksvav43/
So when I return the view I got this error:
I tried to put console.logs to see if the view is rendered but is not rendered...
Ok the error is here:
#model PortalSOCI.WEB.ViewModels.IIT.ExpedienteContainerVM
#{
ViewBag.Title = String.Format(PortalSOCI.WEB.Resources.ExpedienteIIT.TituloExpedienteIIT, Model.Expediente.NumeroExpediente);
}
#section JavaScript /// <-------------------- ERROR
{
#Html.Raw(ViewBag.message)
#
Can you please help me.
edit:
After reading your code, i feel like
#RenderSection("scripts", required: false)
should be
#RenderSection("JavaScript", required: false)
an other thing that I think will give you trouble is the fact that you define your "JavaScript" section in the body. This means that if any of your views you forget to add that
#section JavaScript
{
#Html.Raw(ViewBag.message)
}
you'll get a Section JavaScript not defined error. In your case, feels like the section's definition should be in the _layout.cshtml.
This error most likely means that you have defined the JavaScript section but have not rendered it anywhere.
You need to call #RenderSection("JavaScript") somewhere in your layout.cshtml
the
#section JavaScript
{
}
will let you create a section called "JavaScript", but to actually "print" the content of this section to the output HTML file (that will be sent to the client) you need to call #RenderSection("JavaScript"). The content of the section will be printed where the call to RenderSection is located.
You need to put the missing section inside your ExpedienteIIT view. According to the error message, that missing section is JavaScript.
Code sample, put this at the bottom of your view:
#section JavaScript
{
// put javascript here
}
EDIT:
Thank you for providing a code sample of your views. There is a mismatch between how the JavaScript section in your layout page is defined and how it is being included in your view.
To fix this, do either one of the following:
In your _Layout page, change #RenderSection("scripts", required: false) to #RenderSection("JavaScript", required: false), OR
In your ExpedienteIIT view, change #section JavaScript to #section scripts
The important thing is that the two should match.

0x800a1391 - JavaScript runtime error: 'jQuery' is undefined

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>

HTML helpers in ASP.NET MVC 3 with Javascsript action

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>
}

Add CSS and JS in AJAX-loaded PartialView

I found many answers about similar topics but all refers to PartialViews loaded not by AJAX where solutions are e.g. HtmlHelpers or Head section, but it doesn't work when I load PartialView by AJAX.
I wanna add CSS stylesheet and JS script inside AJAX-loaded PartialView. Now I coded it inside PartialView and it works but it's not good solution (include scripts and stylesheets inside body).
Everything should work just fine except validation. You need to tell jQuery about your new content on order to validate it.
See
ASP.Net MVC: Can you use Data Annotations / Validation with an AJAX / jQuery call?
If you are only loading the PartialView once onto the page, there should be no problem including the scripts and CSS in the body. Like Adam said if you are including a HTML Form dynamically you just have to tell jQuery about it see here ASP.Net MVC 3 client side validation with a dynamic form
However if you want to include the same PartialView multiple times on to the page and do not want to load the script multiple times. Then there are dynamic script loaders you can use that:
You can call just one from your main page, when you load the AJAX so that it is only included once
Include a check to make sure the same script is not loaded multiple times.
I didn't know that earlier that using script tag inside body is not evil. So it's not that bad I thought at first.
I implemented two functions in cssLink.js which I include in head:
/// <reference path="../jquery-1.4.4.js" />
function addCssLink(link) {
var _cssLink = '<link rel=\"stylesheet\" href=\"' + link + '\" type=\"text/css\" />';
$head = $('head');
$link = $('link[href=' + link + ']', $head);
if ($link.length == 0) {
$head.append(_cssLink);
}
}
function removeCssLink(link) {
$('head link[href=' + link + ']').remove();
}
and I use those functions within PartialViews:
<script type="text/javascript">
$(document).ready(function () {
$('#sideMenu').tabs('#content', '#content > *');
addCssLink('/Content/SideMenu.css');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
removeCssLink('/Content/SideMenu.css');
});
</script>
Thank you guys for help, I think that informations about validation should be helpful for me later :)

ASP.NET MVC: How to close browser window instead of returning a view?

I have an instance where, not by my own choice, but I have a secondary popup window in the browser.
Upon form submission back to a server-side MVC method, after this method is complete I'd like it to close that browser window that called it.
Is there a way to do this other than to return a view with javascript in the "onReady" that tells it to close?
No, there isn't a way to achieve this from the server without using javascript (or returning a view that will execute this javascript).
Put this in your view:
#if (ViewBag.ShouldClose) {
<script type="text/javascript">
window.close();
</script>
}
Then if you set the ShouldClose property, it'll run that script and should close the window.
// in your controller
ViewBag.ShouldClose = true;
Note: I did this from the editor so you might have to tweak the view syntax to get it to parse right.
I had the same question and the answer of #Michael Kennedy was exactly what I needed! Since I am using MVC 2 I did have to alter the syntax. I'll put it here as a reference for others.
In the view:
<% if ((bool)ViewData["ShouldClose"]) { %>
<script type="text/javascript">
window.close();
</script>
<% } %>
In the controller:
ViewData["ShouldClose"] = true;
Don't forget to set the ViewData in each call to the view otherwise you'll get a NullReference for the cast to bool.

Categories

Resources