Reputation: 444
I have this script in my view:
@if(ViewBag.UserName != null)
{
<script type="text/javascript">
$(function(){
var msg = 'Welcome, @Encoder.JavaScriptEncode(ViewBag.UserName, false)!';
$("#welcome-message").html(msg).hide().show('slow');
})
</script>
}
However, I want to put the Javascript in a separate file, but when I do that the Html Helper "Encoder" won't work obviously, how would I do a work around so that I still have the Encoder but with the Js in the separate file?
Upvotes: 1
Views: 302
Reputation: 6569
Bundle your javascript files, you should get in a habit of doing this anyway. Bundling helps you manage versions of the files (so that the cached files get refreshed when you update them) and also it can minify the files for you, making your data served faster to the clients.
In your App_Start folder, there is a file called BundleConfig.cs It will look something like this:
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
/* ===================================== Scripts ===================================== */
bundles.Add(
new ScriptBundle("~/Script/JQuery/JQuery")
.Include("~/Scripts/JQuery/jquery-{version}.js")
);
bundles.Add(
new StyleBundle("~/bundles/styles/highslide")
.Include("~/Highslide/Highslide-ie6.css")
.Include("~/Highslide/Highslide.css")
);
}
}
In the example above, we are including a javascript file (version here is automatically populated by the framework) and a css library called Highslide. You can see that in this library we can include multiple files. Also, notice how the files are all in different directories. This allows you to structure your project as you see fit.
Now in order to use this in your view all you have to do is this:
@Scripts.Render("~/Script/JQuery/JQuery")
@Styles.Render("~/bundles/styles/highslide")
With that said, you can now in your view do this:
@if(ViewBag.UserName != null)
{
@Scripts.Render("~/Script/JQuery/JQuery")
}
As for Html encoder issue, why not simply put a javascript variable inside your JS file and then declare and set the variable in the view before you include the file. Like this:
@if(ViewBag.UserName != null)
{
<script type="text/javascript">
var msg = 'Weclome, ' + @Encoder.JavaScriptEncode(ViewBag.UserName, false)!;
</script>
@Scripts.Render("~/Script/MyScript")
}
Your script file can then look like this:
$(function(){
$("#welcome-message").html(msg).hide().show('slow');
})
Upvotes: 1
Reputation: 943143
Either:
<meta>
element or a data-*
attribute) and then read it with the JSUpvotes: 2