Reference JavaScript Files that are in the views folder - MVC 5 - javascript

It is a standard in my company to place the JavaScript file that is uniquely associated with one page or view in the same folder where that page or view resides. Now that we are migrating to MVC we want to keep doing that. For example, if there is a file
~/Views/Customer/CustomerMgmt.cshtml
I need to be able to reference the following associated script file:
~/Views/Customer/CustomerMgmt.js
This js file has functionality that ONLY pertains to CustomerMgmt.cshtml the file will not be shared and thus no other consumer will make use of it. If I reference the JavaScript file using the following, it fails with a 404 error:
<script type = "text/JavaScript" src = "#Url.Content( "~/Views/Customer/CustomerMgmt.js" )">< /script>
The solutions I tried after researching include:
Add the JavaScript reference to BundlerConfig.RegisterBundles and use Scripts.Render in the CsHtml: I still get a 404 error.
Remove the filter that comes with ~/views/web.config:
< add name="BlockViewHandler" path="" verb="" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" / >
This option allows me to reference ~/Views/Customer/CustomerMgmt.js but it is unsecure
Use blacklisting instead of whitelisting to only block *.CsHtml files: This would potentially allow other extensions that may be added in the future and not only *.Css and *.Js
Add the following to the handlers section:
< add name="JavaScriptHandler" path=".js" verb="" preCondition="integratedMode" type="System.Web.StaticFileHandler" / >
I still get a 404 error.
Add custom code to be able to reference the files I need (Helpers, jScript controllers, etc.)
I opted to use the following instructions that modify ~/views/web.config:
Add the following inside < system.webServer >< handlers>:
< add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler"/ >
< add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler"/ >
Add the following inside < system.web>< httpHandlers>:
< add path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" / >
< add path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" / >
< add path="* " verb="*" type="System.Web.HttpNotFoundHandler" / >
After I make this change I get a 500 error and the following (in brief):
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode
And I’m presented with the following suggestions:
a. Migrate the configuration to the system.webServer/handlers section
b. Ignore this error by setting < system.webServer >, < validation validateIntegratedModeConfiguration="false" / >
c. Switch the application to a Classic mode application pool
After using the option “b” everything seems to work fine and I’m able to reference ~/Views/Customer/CustomerMgmt.js but I see several posts suggesting that this is not the best approach.
My questions are:
What is the best approach to follow for this case? I’m using MVC 5.2.3
Is the practice of putting a uniquely associated js file in the same folder as the view considered a bad practice? This file will ONLY be used by a particular view and we don’t want to clutter the ~/Scripts folder (or subfolders within).
I know that I can also create a new folder structure like “~/ViewScripts/…” and put the associated js files there. I will do that if necessary but, if possible I would like to keep adhering to the company standards and put the file, that is only being used by a particular view, together with that view.
Thanks to everyone in advance. Some of the items that I researched include:
MVC - Accessing css, image, js files in view folder
Placing js files in the views folder
How to reference javascript file in ASP.NET MVC 2 Views folder?
Where to put view-specific javascript files in an ASP.NET MVC application?
Cannot load resource MVC 4 JavaScript
Can I deploy a javascript file within MVC areas?
Serving static file on ASP.NET MVC (C#)
Serving static file on ASP.NET MVC (C#)

From this forum I managed to get some code that seems to do the job. I'm using it in a ViewComponent. I have a folder for the component and wanted to consolidate all the files in one folder, e.g.
\Component\
\Component\Component.cshtml
\Component\Component.js
\Component\ComponentModel.js
\Component\ComponentController.js
Assuming a consistent naming convention, I loaded it with this, which doesn't require any changes to web.config nor does it open up the client to loading other .js files.
<script>
#{ Html.RenderPartial(Regex.Replace(ViewContext.ExecutingFilePath, #"\.[^.]+$", #".js")); }
</script>

Related

Only js file per page in laravel

In a Laravel setup using Laravel mix, the mix.js(['resources/js/app.js','resources/js/new-offer.js'], 'public/js') puts everything in one file, app.js.
What I am trying to achieve is to have multiple .js files each for one page. For example. I want to have index.js for my index.blade.php and new-offer.js for my new-offer.blade.php etc ...
The idea is that each page is server side rendered and each page represents a static page comming fromm the server and each one should has it's own set of js files that works in. How this should be done, is it recommended, what are other arhcitectures ?
You can use multiple concatenated .js(...) statements. In your case:
mix.js('resources/js/app.js','public/js').js('resources/js/new-offer.js' ,'public/js')
This will createapp.js and new-offer.js files in your public js folder

angularjs routing not working in proprietary browser

First, let me say you will not be able to reproduce my problem unless you also are working in a healthcare situation using the latest athenaPractice EMR.
I just don't have any direction on where to troubleshoot this problem and looking for suggestions for what information or settings I should be checking.
I have an AngularJS SPA set up that routes 100% fine in a regular Chrome browser window locally served (http-server installed via npm). I can load the main app page by URL (localhost:port/app, which redirects to /app/#!) and I can load the subpage by URL (localhost:port/app/#!/page). I can do it with or without a trailing /. I can navigate from one view to the other by links on the page. Works great.
But I have a problem when I put it in the server location (which, if it's relevant, has a path longer than /app/ from the //localserver/ root), and load the file through the EMR (which is running Chromium). (Files are loaded in the EMR by adding a specially formatted file that links all included items in a form, which in the case of HTML files, is just a URL to a resource: //localserver/directory/subdirectory/app/#!/page). It loads fine the first time, but if I try to load separately a different page (//localserver/directory/subdirectory/app/#!/, for example), it shows the currently open page. It's almost like both instances of the browser are the same browser window and it doesn't bother to load a new window for the URL with the same address up to the #!. I can navigate from one page to another by links but not by loading from the root address, and if I navigate under one "form", and click back to the other one, it's also been navigated, hence why I think it's only one instance of the window.
I tried HTML5 routing with no success since this is running in a JBoss 7.x server and I have had a very hard time finding any documentation that even comes close to matching the files I see on the server for URL rewriting access. (I have found instructions that reference files that don't exist in our installation, so I don't know if this has been customized by the application provider, or what.)
I don't have access to developer tools, console, or even the address bar through the EMR.
Any suggestions on where to go with troubleshooting this?
Edit to add: Might be worth noting that I have tried ngRoute and ui-router both with the same results.
I got this working correctly. I don't know what the root cause in the EMR is, but it was treating each loaded route of the SPA as part of the same instance using #! routes. Getting HTML5 routing working solved the issue.
After fighting with Undertow for a day and having no feedback on why my rules weren't working, I ended up using Tuckey's URL Rewrite. It helpfully logs what input it was comparing against what which allowed me to see where my first attempts at rules went wrong, and edit them accordingly until they worked.
This required three file changes in the WEB-INF directory inside the application's .war directory. (There are various META-INF and WEB-INF directories all over in this setup but using this one worked in the specific deployment I'm working in now, namely our demo server.)
Create a /lib directory inside WEB-INF and put urlrewritefilter-4.0.4.jar in it (downloaded from the Maven repository)
Put the example urlrewrite.xml into WEB-INF and adapt it with necessary rules. For the root page of our SPA and the first route, the custom rules I inserted look something like this:
<rule match-type="regex" enabled="true">
<condition type="request-filename" operator="notfile" />
<condition type="request-uri" operator="notequal">(\.html|\.js|\.css)</condition>
<from>^/FormsFolder/subfolder/app/$</from>
<to last="true">/FormsFolder/subfolder/app/index.html</to>
</rule>
<rule match-type="regex" enabled="true">
<condition type="request-filename" operator="notfile" />
<condition type="request-uri" operator="notequal">(\.html|\.js|\.css)</condition>
<from>^/FormsFolder/subfolder/app/route1/$</from>
<to last="true">/FormsFolder/subfolder/app/index.html</to>
</rule>
Add the Tuckey Rewrite Filter to web.xml:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confPath</param-name>
<param-value>/WEB-INF/urlrewrite.xml</param-value>
</init-param>
<init-param>
<!-- This configures how often to check for an update to urlrewrite.xml -->
<param-name>confReloadCheckInterval</param-name>
<param-value>60</param-value>
</init-param>
<init-param>
<!-- This configures what detail level of messages to log. TRACE was useful to
figure things out but DEBUG or WARN is probably more appropriate for production -->
<param-name>logLevel</param-name>
<param-value>TRACE</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Lastly I had to update the index.html of the SPA to include the base tag, before all the stylesheet links and javascript script includes so that they route correctly. For the demo server, mine looks something like <base href="/demo/ws/FormsFolder/subfolder/app/"> but will have to be updated to publish to the live server.
Hopefully this is helpful if anyone else is trying to configure HTML5 routing on a similar JBoss server.

How can I add a .js file to an assembly in an ASP.NET project

I have an ASP.NET 4.5 WebForms project in VS 2013 and I need a function to clear the contents of all text boxes on a button click. I want to obviously do this client side so need javascript. I can't find this function in any of the preinstalled js files or jquery or bootstrap etc, so I need to create my own.
Fine. So I've created the js file with the function in it.
I added a reference in the _references.js file and I have added a script reference in my master page
However, when I run I get an error:
Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx' does not contain a Web resource with name 'CustomerDetails.js'.
I don't have the option to add to an assembly in the properties of customerdetails.js (as this is a webforms project).
Can anyone tell me how to add to / create an assembly to reference this js file?!!
Muchos Gracias
If you want to add file to assembly, you should add it to resource file. But is it real need to embed script to the resource of assembly? Since your application uses asp.net you can just copy this script to specified folder and configure your script manager to handle it.

HTML/Javascript: Enabling folder access from a subdirectory

I have a simple HTML file with some JavaScript that I would like to run locally (as opposed to deploying to a server). It is embedded inside a larger project whose file structure I would like to maintain. For example, the structure is something like this:
project level folder > src folder containing folders & files I would like to probe
> separate, non-project util folder > HTML & JS files I would like to run against src
I am aware that certain browsers do not allow this for security reasons (as pointed out here), but since I control all of the files - is there a way for the src folder/files to somehow indicate that they will allow the 'separate, non-project util folder' to access them? Maybe some kind of project-specific settings somewhere? I am aware that this can be done in server settings, but as I mentioned above I'd like to be able to run it locally without the need for a server.
The JavaScript that is attempting to access the src files uses RequireJS, in case that helps.
Here is what I ended up doing:
I wasn't able to provide full access exactly this way, but instead I setup a dummy HTML page in the project level folder that clicks itself to redirect to the HTML file located in the separate, non-project util folder. This allowed me to keep everything but that one, very small file separate but not have issues with file access.

How to get resource in WEB-INF JSP/Struts

There are JSP pages in a folder called 'jsp' inside the WEB-INF. Those pages need some javascript files. In JSP page, javascript files are called
<script type="text/javascript" src="../../app.lib/jQuery-v-1-7-2.js"></script>
but the browser cannot access this resource. All requests to the JSP pages inside the web-inf go through an action and seperate name space also has been given for that pages called 'secure'.
Lets say that, this account.jsp page needs a javascript file which locates in a folder called 'app.lib' inside the 'web' folder.(out of web-inf) .
(1) I want to know a way to retrieve that javascript file into account.jsp page using struts actions or another jsp functionality.
(2) second question is: Lets say, there are images which should be secured, and the application itself should be able to send them to the browser when requested.In other words, images inside a folder in WEB-INF, then how can I access them in account.jsp?
This is the web.xml(session configuration and welcome file list tags removed for clear view)
<?xml version="1.0" encoding="UTF-8"?>
<web-app.......>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
This is the project structure
Don't put your JavaScript files inside the WEB-INF folder. JSP pages kept in WEB-INF are accessed by the servlet-container, processed, and then rendered to the client via the servlet, which has access to files in WEB-INF. JavaScript files are client side resources, and since the client side cannot access any resources inside WEB-INF, they must be located outside that folder.
Typically, it's common to put your JavaScript files in a folder called "js", like so:
-/js
- actions.js
-/WEB-INF
- /jsp
- abc.jsp
As an aside, since JavaScript is client side, even if you were to go through the trouble of storing them in the WEB-INF folder and using the servlet engine to process them, any user would still be able to access the resource URL and view the source. Essentially, you gain no benefit from this and only incur costs, both in maintenance and additional development overhead.

Categories

Resources