I worked with two jquery libraries in MVC 4 project which worked fine.
Now i building the same web site using MVC 5 + web api + durandel and knockout.
But i dont know how to insert those libraries:
http://www.3quarks.com/en/SegmentDisplay/
http://brandonlwhite.github.io/sevenSeg.js/
I want to insert them in a table ( foreach)
the JS is in require as define module
and not in the HTML file,
i dont know how to start and need help please.
As per the documentation, include the following libraries :
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<script src="sevenSeg.js"></script>
Either directly in your index.html file, or via the RegisterBundles method in file in your App_Start folder :
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(
new ScriptBundle("~/Scripts/vendor")
.Include("~/Scripts/jquery-2.0.2.js")
.Include("~/Scripts/jquery-ui-1.10.3.js")
.Include("~/Scripts/knockout-3.3.0.debug.js")
.Include("~/Scripts/sevenSeg.js")
);
}
Then include it in your index file :
#Scripts.Render("~/Scripts/vendor")
Then you should be able to use the SevenSeg data binding like this :
<div data-bind="sevenSeg: {digits: 5, value: testValue1}"></div>
If the data binding does not work, you would have to create a custom binding handler in an external file (eg /Scripts/sevenSegCustom.js and load your custom binding in your main.js file like this :
define(['sevenSegCustom'], function(sevenSegCustom) {
composition.addBindingHandler('myCustomSSBinding', sevenSegCustom.sevenSegCustom)
}
Then use it like this :
<div data-bind="myCustomSSBinding: {digits: 5, value: testValue1}"></div>
Hope it helps !
Related
I have a simple HTML file:
<html>
<head>
<script async src="https://URL"></script>
</head>
<body>
<div class="class-name"></div>
</body>
</html>
When I access it with a browser using Windows: C:\foo.html?q=query the file loads correctly.
When I access the same file, that I have added it to my Android project in the Assets directory, with a Custom WebView and a Custom Renderer in my Xamarin.Forms project like this: myCustomWebview.Uri = "foo.html" + "?q=" + queryString; the Javascript fails to populate the div in the body correctly. The same problem exists if I load the file without a query string: myCustomWebview.Uri = "foo.html";
What's the deal? Do I need to set any special Permissions in the AndroidManifest.xml for the Javascript to work properly? Do I need to set a specific BuildAction in the file properties of the HTML file in my Android project? Do I need to do something else?
Place html file into Assets directory with build action AndroidAsset .
Use DependencyService to set the exact path .
[assembly: Dependency (typeof(BaseUrl_Android))]
namespace WorkingWithWebview.Android
{
public class BaseUrl_Android : IBaseUrl
{
public string Get()
{
return "file:///android_asset/";
}
}
}
Set BaseUrl to HtmlWebViewSource and pass it to WebView.Source .
var source = new HtmlWebViewSource();
source.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
webView.Source = source .
Refer to
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=windows#local-html-content.
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.
Code for clarity:
define([], function () {
var serviceBaseUrl = 'http://localhost/Service/api/';
var portalPortalUrl = 'http://localhost/Portal';
});
And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.
What I want:
To store them in Web.config file so I can have different configuration for debug and release modes.
I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.
I have only found solutions using ASP.NET ConfigurationManager like so:
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
Or, for Razor:
#System.Configuration.ConfigurationManager.AppSettings["myKey"]
It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.
If needed, here is my project structure:
- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
You can use JavaScriptResult
Sends JavaScript content to the response.
Code, Controller Action method
public JavaScriptResult Config()
{
var script = string.Format(#"var configServiceBaseUrl = {0};", ConfigurationManager.AppSettings["var1"]);
return JavaScript(script);
}
In the page header(I would load the file first), You can define:
<script type="text/javascript" src='#Url.Action("Config", "Controller")'></script>
Now configServiceBaseUrl is Global JavaScript variable which you can use anywhere.
So you can use configServiceBaseUrl in url.config.js like
define([], function () {
var serviceBaseUrl = configServiceBaseUrl;
});
Adding to satpal, for SPA application such as angular js
For SPA's, such as angular you can use below code in your index.html as
<script type="text/javascript" src='/Controller/config'></script>
Constraints: I'm not using MVC, just regular ol' .aspx files in my web app. Not using master pages either - each page is a different beast, so that solution isn't right for me.
Most examples I've read for bundling and minification require either some special MVC markup or require you to identify the bundled scripts / stylesheets up front and then refer to these bundles. I want to avoid recompiling DLLs every time I add or modify a .js reference in a .aspx page.
I'm a bit stumped from reading the Msft docs.. is there a way (like an ASP.NET control) that I can just wrap a series of script tags (or link tags for CSS) to create and use a bundle dynamically? I don't want to reinvent the wheel, but seriously considering creating my own user control / custom control that handles this. Are there other options?
For example, looking for something like this:
<asp:AdHocScriptBundle id="mypage_bundle" runat="server">
<script type="text/javascript" src="~/scripts/mypage1.js"></script>
<script type="text/javascript" src="~/scripts/mypage2.js"></script>
<script type="text/javascript" src="~/scripts/mypage3.js"></script>
</asp:AdHocScriptBundle>
that, when bundling is enabled, automatically replaces the contents of asp:AdHocScriptBundle with a single script tag that resembles this:
<script type="text/javascript" src="/webappname/bundles/mypage_bundle.js?v=dh120398dh1298dh192d8hd32d"></script>
And when Bundling is disabled, outputs the contents normally like this:
<script type="text/javascript" src="/webappname/scripts/mypage1.js"></script>
<script type="text/javascript" src="/webappname/scripts/mypage2.js"></script>
<script type="text/javascript" src="/webappname/scripts/mypage3.js"></script>
Any thoughts?
About to roll my own anyway, but if there is already a solution for this please share, thanks!
I rolled my own solution and it works great! I created 4 classes that I can use as custom server controls:
ScriptBundle
Script
StyleBundle
Link
These call functions around my custom bundling library which is itself a wrapper for the System.Web.Optimization API.
During Render of ScriptBundle and StyleBundle I then check an internal setting (the same one that I use to set EnableOptimizations in the System.Web.Optimization API) that tells the page to either use bundling, or simply write out the normal script / link tags. If Bundling is enabled it calls this function from my custom bundling library (for Scripts, similar code for Styles tho. Bundler in code below is the class for my custom bundling library - just in case Microsoft changes the System.Web.Optimization API I wanted a layer in-between so that I wouldn't have to change my code as much):
public static void AddScriptBundle(string virtualTargetPath, params string[] virtualSourcePaths)
{
var scriptBundle = new System.Web.Optimization.ScriptBundle(virtualTargetPath);
scriptBundle.Include(virtualSourcePaths);
System.Web.Optimization.BundleTable.Bundles.Add(scriptBundle);
}
To make sure that I only create the Bundle if it does not already exist, I first check for the Bundle using this method (before using the above method):
public static bool BundleExists(string virtualTargetPath)
{
return System.Web.Optimization.BundleTable.Bundles.GetBundleFor(virtualTargetPath) != null;
}
Then I use this function to spit out the URL to the bundle by using System.Web.Optimization:
public static System.Web.IHtmlString GetScriptBundleHTML(string virtualTargetPath)
{
return System.Web.Optimization.Scripts.Render(virtualTargetPath);
}
Within my .aspx files, I do this:
<%# Register TagPrefix="cc1" Namespace="AdHocBundler" Assembly="AdHocBundler" %>
...
<cc1:ScriptBundle name="MyBundle" runat="Server">
<cc1:script src='~/js/script1.js'/>
<cc1:script src='~/js/utils/script2.js'/>
</cc1:ScriptBundle>
The trick for me was figuring out that I had to convert script and link tags to be work as list items within the ScriptBundle and StyleBundle controls, but after that it works great AND it let me use the tilde operator for easy references relative to app root (using Page.ResolveClientUrl(), which is helpful for creating module content).
Thanks go to this SO answer for helping me figure out how to create a custom collection control: How do you build an ASP.NET custom control with a collection property?
UPDATE: In the interest of full disclosure, I got permission to share the code for ScriptBundle (StyleBundle is almost identical, so did not include it):
[DefaultProperty("Name")]
[ParseChildren(true, DefaultProperty = "Scripts")]
public class ScriptBundle : Control
{
public ScriptBundle()
{
this.Enabled = true;
this.Scripts = new List<Script>();
}
[PersistenceMode(PersistenceMode.Attribute)]
public String Name { get; set; }
[PersistenceMode(PersistenceMode.Attribute)]
[DefaultValue(true)]
public Boolean Enabled { get; set; }
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public List<Script> Scripts { get; set; }
protected override void Render(HtmlTextWriter writer)
{
if (String.IsNullOrEmpty(this.Name))
{
// Name is used to generate the bundle; tell dev if he forgot it
throw new Exception("ScriptBundle Name is not defined.");
}
writer.BeginRender();
if (this.Enabled && Bundler.EnableOptimizations)
{
if (this.Scripts.Count > 0)
{
string bundleName = String.Format("~/bundles{0}/{1}.js",
HttpContext.Current.Request.FilePath,
this.Name).ToLower();
// create a bundle if not exists
if (!Bundler.BundleExists(bundleName))
{
string[] scriptPaths = new string[this.Scripts.Count];
int len = scriptPaths.Length;
for (int i = 0; i < len; i++)
{
if (!string.IsNullOrEmpty(this.Scripts[i].Src))
{
// no need for resolve client URL here - bundler already does it for us, so paths like "~/scripts" will already be expanded
scriptPaths[i] = this.Scripts[i].Src;
}
}
Bundler.AddScriptBundle(bundleName, scriptPaths);
}
// spit out a reference to bundle
writer.Write(Bundler.GetScriptBundleHTML(bundleName));
}
}
else
{
// do not use bundling. generate normal script tags for each Script
foreach (Script s in this.Scripts)
{
if (!string.IsNullOrEmpty(s.Src))
{
// render <script type='<type>' src='<src'>/> ... and resolve URL to expand tilde, which lets us use paths relative to app root
// calling writer.Write() directly since it has less overhead than using RenderBeginTag(), etc., assumption is no special/weird chars in the cc1:script attrs
writer.Write(String.Format(Script.TAG_FORMAT_DEFAULT,
s.Type,
Page.ResolveClientUrl(s.Src)));
}
}
}
writer.EndRender();
}
}
public class Script
{
public const String ATTR_TYPE_DEFAULT = "text/javascript";
public const String TAG_FORMAT_DEFAULT = "<script type=\"{0}\" src=\"{1}\"></script>";
public Script()
{
this.Type = ATTR_TYPE_DEFAULT;
this.Src = null;
}
public String Type { get; set; }
public String Src { get; set; }
public String Language { get; set; }
}
This isn't possible with the default Bundling/Minification in ASP.NET. The entire point of bundling is to create one single to file to reduce the number of browser requests to load static files such as .JS and .CSS files.
Rolling your own is your only option. However, please note that each <script> line will result in a browser request. Since most browsers can only handle 6 requests concurrently, you can have wait times just to load these static files.
And FYI, you don't have to recompile DLLs every time you update your .JS files with built-in bundling. You can simply reset the application pool the app is running on. If you're running with an external session persistence model, your users won't notice when this happens.
Your problem here is that you aren't really thinking this problem through. If you were, you would realize that what you are asking for can't work.
Why? Because the script tag ahs to generate an external link reference to a different url. So anything you place in the header of the current file will have no affect on your other URL that actually contains your bundles. As such, there is no way to dynamically change your bundles in the page itself because bundles have to, by definition, be defined in an external resource.
Now, there's nothing that says those bundles have to be compiled into DLL's in your own solution, but they cannot be embedded in the page that's currently being rendered.
You might want to investigate some of the javascript based minification tools out there, since they are typically not compiled.
Is there any tool to make adding files to MVC3 razor pages faster?
I find myself having to drag script files onto the page to generate:
<script src="../../Scripts/rails.js" type="text/javascript"></script>
Which then i'll copy and paste
<script src="#Url.Content("~/Scripts/")" type="text/javascript"></script>
Then cut/drag the rails.js fragment into the new script statement. Then at some point after this hopefully I remember I need to clean up a whole bunch of duplicated and/or broken script links.
There has to be a better way than this that doesn't involve typing urls out manually.
Came across this blog post earlier today and ASP.NET MVC Best Practices (Part 1) and it's guidance shows
public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/images/{0}".FormatWith(fileName));
}
public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/stylesheets/{0}".FormatWith(fileName));
}
public static string NoIcon(this UrlHelper helper)
{
return Image(helper, "noIcon.png");
}
This seems like the optimal solution if you use a good layout scheme for your resources.
Edit: FWIW
public static string FormatWith(this string format, params object[] inputs)
{
return string.Format(format, inputs)
}
You can use T4MVC to get a compile-time validation your your links.
2.3. Strongly typed links to script files and static resources
T4MVC generates static helpers for
your content files and script files.
So instead of writing:
<img src="/Content/nerd.jpg" />
You
can write:
<img src="<%= Links.Content.nerd_jpg %>" />
Likewise, instead of
<script src="/Scripts/Map.js" type="text/javascript"></script>
You
can write
<script src="<%= Links.Scripts.Map_js %>" type="text/javascript"></script>
The obvious benefit is that you’ll get
a compile error if you ever move or
rename your static resource, so you’ll
catch it earlier.
Another benefit is that you get a more
versatile reference. When you write
src="/Content/nerd.jpg", your app will
only work when it’s deployed at the
root of the site. But when you use the
helper, it executes some server side
logic that makes sure your reference
is correct wherever your site is
rooted. It does this by calling
VirtualPathUtility.ToAbsolute("~/Content/nerd.jpg").
I have a Master Page in the root of my project. I have Content Pages throughout my project and in subfolders referencing this Master Page. What is the correct way to reference my .CSS and .JS files if I always want them to be relative to the root?
Here is how I'm doing it now:
link href="/common/css/global.css"
script src="/common/javascript/global.js"
But that breaks the link. I tried without the leading "/" but that didn't work on my pages in the subfolders.
I would use something like
Server.ResolveClientUrl("~/common/css/global.css")
This will get a proper url for you at all times.
Example:
Per the comment this would be full usage.
<link type="text/css" rel="stylesheet"
href='<%= Server.ResolveClientUrl("~/common/css/global.css") %>' />
According to comments, other validated usage, no "error CS1061: 'System.Web.HttpServerUtility' does not contain a definition" error:
<script type="text/javascript"
src="<%= Page.ResolveUrl("~/Scripts/YourScript.js") %>" ></script>
Also is important to always put the closing tag .
You can make the <link> tag to run at server so Asp.Net will resolve the URL for you like this:
<link href="~/common/css/global.css" runat="server" />
(Notice the '~')
I don't know if it can be applied to the <script> tag though, you should try...
EDIT: I discovered recently on a project that you can (and should) use a ScriptManager to hold your scripts (you can only have 1 per page). You can put one in your MasterPage and reference all your scripts. Inside your content page, you then add a ScriptManagerProxy that will 'reference' the scripts on the master page and you can even add other scripts for that content page only.
I do it as simple as this: link href="<%=ResolveUrl("~/common/css/global.css")%>"
The solutions I saw so far didn't work in my project (especially not for .css links). The issues were the following:
inside <link> it didn't resolve the <%=...%> expression
it did not find the Page.ResolveURL in all cases
there was some trouble with ' and " quotes if you embedd <%=...%>
So I'd like to offer this solution: In code behind (your master page's C# class), add the the following 3 methods:
public partial class SiteBasic : System.Web.UI.MasterPage
{
public string ResolveURL(string url)
{
var resolvedURL=this.Page.ResolveClientUrl(url);
return resolvedURL;
}
public string cssLink(string cssURL)
{
return string.Format("<link href='{0}' rel='stylesheet' type='text/css'/>",
ResolveURL(cssURL));
}
public string jsLink(string jsURL)
{
return string.Format("<script src='{0}' type='text/javascript'></script>",
ResolveURL(jsURL));
}
}
For stylsheet references, you can then say:
<%=cssLink("~/css/custom-theme/jquery-ui-1.8.20.custom.css")%>
For JavaScript references, it looks like so:
<%=jsLink("~/Scripts/jquery-1.7.2.js")%>
And for other references, you can use:
<a href='<%=ResolveURL("~/Default.htm")%>'>link</a>
<img title='image' src='<%=ResolveURL("~/Images/logo.png")%>'/>
Note: I found it is better to use single quotes outside and double quotes inside the href or src attribute as shown in the example above. Doing it vice versa caused trouble in some cases as I found.
This solution is simple and it worked well in my case, even if the pages referencing the master page reside in different subdirectories. What it basically does is translating the ~ path (which needs to be absolute from the root of your web site) into a relative path (using as many ../ in the path as needed) based on the page you're currently displaying.
Advanced hint:
If you're using AJAX calls to invoke web service methods, then you'll have the same issue referencing them if you have ASPX pages on different directory levels. I recommend you define something like (assuming that your web services reside in the directory ~/AJAX):
<script type="text/javascript">
function getWebServicePath() { return '<%=ResolveURL("~/AJAX/")%>'; }
</script>
inside the <head> ... </head> section of your master page. This will make the entry path of the web service available in your JavaScript. You can use it like
$.ajax({
type: "POST",
url: getWebServicePath()+"myWebService.asmx/myMethod",
data: $.toJSON({ param: "" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// ... code on success ...
},
error: function (ex) {
// ... code on error ...
}
});