"JavaScript Hell" - Like "DLL Hell" [duplicate] - javascript

This question already has answers here:
force browsers to get latest js and css files in asp.net application
(23 answers)
Closed 7 years ago.
I have an ASP.NET webpage, which looks like this:
<%# Page Language="VB" MasterPageFile="~/LGMaster.master" AutoEventWireup="false" Inherits="com.Genie.PresentationLayer.Web.frmPNList" title="Primary Nominals results list - RESTRICTED" Codebehind="frmPNList.aspx.vb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="Javascript/json2.js"></script>
<script type="text/javascript" src="Javascript/massusnchange1014.js"></script>
<script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:PlaceHolder runat="server" ID="NextBits" />
<%--<input id="btnSave" type="button" value="Group USN Change" onclick="GroupUSNChange();"/>--%>
<%--<asp:Button ID="ButtonSetUSN" runat="server" Text="Set USN" OnClientClick="GetNewUSN()"></asp:Button>--%>
<asp:HiddenField ID="hfUSN" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="hfGenieConnectionString" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="hfUserName" ClientIDMode="Static" runat="server" />
<button onclick="GetNewUSN()">Change USN of Group</button>
</asp:Content>
Each time I make a change to: massusnchange1014.js I have to increment it by 1 e.g. the next revision will be: massusnchange1015.js, otherwise I get errors implying the asp.net webpage is using the last revision.
Why is this?

Because your browser is helping you out by caching the content. Like a picture it's seen before, the browser caches the response it got back for a URL. If the URL changes, it goes and gets the content again. Otherwise, it has no idea you've changed it.
You have a couple of options.
Use ASP.NET's ClientScriptManager to bundle your JS - it handles changes like this.
if you need them to stay as individual files, you could append a timestamp from the file on the URL to produce new URLs.

Related

Cannot set property 'value' of null in javascript

I am getting the following error "Cannot set property 'value' of null" in the javascript named as "item_pricecataglog.js", following the line of code
document.getElementById('ctl00_ContentPlaceHolder1_ctl00_hdn_returnboolvalue').value = 'true';
I assume this is because my application did not find the corresponding element in the web page or control.
strange thing is, element "hdn_returnboolvalue" is declared in the web control from where this java script is referenced. below is the snippet of my web control
<%# control language="C#" autoeventwireup="true" CodeBehind="EstimateProductcatalogueBind.ascx.cs" Inherits="ePrint.usercontrol.ProductCatalogue.EstimateProductcatalogueBind" %>
<script type="text/javascript" src="<%=strSitepath %>js/item/item_pricecatalog.js"
language="javascript"></script>
<div>
<asp:HiddenField ID="hdn_kitavailibility" runat="server" Value="0" />
<asp:HiddenField ID="hdn_returnboolvalue" runat="server" Value="" />
</div>
The above control is inside the popup which is aspx page named "common_popup". i have added the control to "ContentPlaceHolder1" which is declared in popup aspx page.
<%# page language="C#" masterpagefile="~/Templates/popUpMasterPage.master" autoeventwireup="true" CodeBehind="common_popup.aspx.cs" Inherits="ePrint.common.common_popup" title="Untitled Page" enableviewstatemac="false" enableEventValidation="false" theme="Theme1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<script type="text/javascript" language="javascript" src="<%=strSitepath %>js/Item/general.js?VN='<%=VersionNumber%>'"></script>
<div>
<UC:callClass ID="usrCallclass" runat="server" />
</div>
<div>
<asp:PlaceHolder ID="plhDiv" runat="server"></asp:PlaceHolder>
</div>
</asp:Content>
below is the snippet of C# code from where i am adding the control to this page
UserControl userControl37 = (UserControl)base.LoadControl("~/usercontrol/ProductCatalogue/EstimateProductcatalogueBind.ascx");
this.plhDiv.Controls.Add(userControl37);
I think the proper code should be (notice the changed id):
document.getElementById('ContentPlaceHolder1_PriceCatalog_hdn_returnboolvalue').value = 'true';

InvalidOperationException: WebForms UnobtrusiveValidationMode in C#

I've a web form with a text box and RequiredFieldValidator Control.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate ="TextBox1" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>
<asp:button runat="server" text="Button" />
</div>
</form>
</body>
</html>
When I load the page and click on the button, I get an error saying
Error:
[InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).]
System.Web.UI.ClientScriptManager.EnsureJqueryRegistered() +145
System.Web.UI.WebControls.BaseValidator.RegisterUnobtrusiveScript() +11
System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +88
System.Web.UI.Control.PreRenderRecursiveInternal() +166
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4682
I did some googling and found some solutions like changing the target version to 4.0 in web.config, using jquery in the global.asax file and changing the property of UnobtrusiveValidationMode to none.
I even read about unobtrusive javascript at https://en.wikipedia.org/wiki/Unobtrusive_JavaScript. But I could not make any relation with the content given there and the error I encountered
Most of the answers said to refer http://connect.microsoft.com/VisualStudio/feedback/details/735928/in-asp-net-web-application-visual-basic-the-requiredfieldvalidator-doest-work
But this link no longer exists.
When I viewed the source of the web page after changing the target version to 4.0, I found some extra inline javascripts(I guess that's called obtrusive javascripts). What's wrong in using inline codes?
I'm pretty new to ASP.net, so little brevity appreciated.

ASP.NET Webcam Display

I'm writing an asp.net site in VB, and am trying to integrate in webcam functionality via javascript. I'm using webcam.js (found here: https://github.com/jhuckaby/webcamjs). When I created a new project for testing this out and working out the kinks, it worked fine. However, when I attempted to integrate it into my main project, the video does not load and I'm left with a blank screen. I can confirm that it does work in the side project in IE, firefox, and chrome, yet works in none of them after integrating it in my main project. The integration process was not complicated, it was mainly just copy and paste and adding the requisite references. I at first was getting problems of it not recognizing 'Webcam' but that went away after I coded in the exact location of the webcam.js file (I understand that this will be a problem later, but I'm more worried about getting it working in debug mode for now so it's fine). My code is as follows:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebcamPart.aspx.vb" Inherits="IMHmfgb_VerJon.WebCamPart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager EnablePageMethods="true" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<script src="location of webcam.js"></script>
<div id="my_camera" style="width:640px; height:480px"></div>
<asp:Label ID="Label1" runat="server" Font-Size="12"></asp:Label>
<script type="text/javascript">
function showCam() {
Webcam.attach('my_camera');
}
</script>
<asp:Button ID="Button2" runat="server" OnClientClick="showCam();return false" Text="Show Cam" /><asp:Button ID="Button1" runat="server" OnClientClick="take_snapshot();return false" Text="Scan" />
<script type="text/javascript">
function take_snapshot() {
Webcam.snap(function (data_uri) {
PageMethods.BarcodeScan(data_uri, onSuccess, onFailure);
})
};
function onSuccess(result) {
document.getElementById('<%=Label1.ClientID%>').innerHTML = result;
};
function onFailure(result) {
document.getElementById('<%=Label1.ClientID%>').innerHTML = result;
};
</script>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="500">
<ProgressTemplate>
<asp:Image ImageUrl="~\Pictures\Loading.gif" runat="server" ImageAlign="Middle" />
</ProgressTemplate>
</asp:UpdateProgress>
</form>
</body>
</html>
I don't believe that the code above is the problem because, as stated above, it all works fine by itself. This leads me to believe that there is some setting or piece of code somewhere in my main project that is interfering with loading the video, but I have no idea where to look or what to look for.
And, after a lot of troubleshooting, I fixed my own problem. Apparently it's not enough to simply state the location of the webcam.js file in the following code block:
<script src="location of webcam.js"></script>
You need to have the webcam.js and webcam.swf files located in the same folder as the page that is using them. I found this out by looking at the error console in chrome. I figured the errors would be the same in IE, and as my site is built to run in IE, I checked there first.

Perform at same time javascript and asp.net rendering

Suppose I have a .gif:
<img alt="" src="./wait.gif" />
And I have a Label:
<asp:Label ID="tbnotif" runat="server" ReadOnly="True" Text="" ></asp:Label>
And a button:
<asp:Button ID="Button1" runat="server" Text="Pubblica" OnClientClick="show_table();add_gif();" OnCommand="Button1_Click" />
I'm using aspx pages, the question is:
Can I click on the button and at same TIME show the .gif with JavaScript and change the Label from code behind? Or will things never be shown at same time?
It looks to me like you want to show a busy animated gif between postbacks, is that right?
Here's how I do it (unless I'm using update panels which have their own progress indicator server control)
<script type="text/javascript">
window.onbeforeunload = function(){showGif();};
</script>
When the page unloads because of a postback (click the button which POSTs to the server), reveal the gif image. When the new page comes back from the server the image will disappear because it's now a new page.
Changing a label is a small operation, so you will probably never see the image as the request/response will turn around very quickly. For testing you can add a System.Threading.Thread.Sleep(3000) in your button handler to simulate a longer running process.
EDIT
AJAX is your only option then, but there are many many ways. One possible solution:
Put the label in an UpdatePanel server control, place button outside of update panel, but set it as an AsyncPostbackTrigger in the update panel's declarative mark-up in the aspx page. Show the gif with OnClientClick handler client-side or using JQuery to attach a client-side click handler to the button.
aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="AjaxLabel._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="ajaxLabel">Initial value</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="asyncButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<img id="theImage" src="img/success.png" style="display: none;" />
<asp:Button runat="server" ID="asyncButton" Text="Client & Server Click" OnClientClick="showImage();" OnClick="asyncButton_Click" />
</div>
</form>
<script type="text/javascript">
function showImage() {
document.getElementById('theImage').style.display = "block";
}
</script>
</body>
</html>
aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxLabel
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void asyncButton_Click(object sender, EventArgs e)
{
ajaxLabel.Text = "Server-side value";
}
}
}

How do I add JavaScript to an ASP.NET MVC View?

I have a simple View and I wish to add a JQuery DatePicker JavaScript to this view (and not every view, via a masterpage).
I'm not sure what is the best way to do this.
Second, I'm conscious of where/when my JavaScript loads. I'm a fan of YSlow and it recommends that I add any scripts to the bottom of the page, which I do.
So, how could I do both?
Here's the view:
<%# Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<% using (Html.BeginForm()) {%>
<p>
<label for="StartDate">Start Date:</label>
<!-- JQuery DatePicker to be added, here. -->
</p>
<% } %>
</asp:Content>
In ASP.NET MVC3, you can now use a RenderSection to achieve this, at least for simpler scenarios. Just add a RenderSection to the bottom of the layout page, and from your view fill in the appliation code
RenderSections: http://www.dotnetcurry.com/ShowArticle.aspx?ID=636
Your MasterPage should have a ContentPlaceHolder for the head.
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server" />
</head>
Then you're able to include head elements (JavaScripts, StyleSheets, etc...) in your views:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="/Scripts/jquery/ui/ui.datepicker.js" type="text/javascript">
</script>
<link href="/Styles/myStyle.css" rel="stylesheet" type="text/css" />
</asp:Content>
One way is put a content placeholder at the bottom of your master page, then the specific slave page that needs the javascript can specify the placeholders contents as the required javascript. Other pages that don't need the javascript simply don't specify any content for the placeholder.

Categories