I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my ~/Views/Shared/Site.Master
):
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with ~/Scripts/...
doesn't work. Starting with /Scripts/...
would only work if the project was at the site root (which I don't want to assume).
I have one working approach (I'll post below) - but: am I missing something?
I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?
Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:
<script src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.
You add a new view master page to an MVC project by right-clicking the Views\Shared folder, selecting the menu option Add, New Item, and selecting the MVC View Master Page template (see Figure 1). You can create more than one view master page in an application. Each view master page can define a different page layout.
JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.
Layout is similar to the master page in ASP.NET Web Form. Similar to master page, the Layouts may contain CSS, jQuery files and multiple views. Layout can keep the user interface elements and theme consistency throughout the application.
I have a AppHelper class with some methods for adding script references:
public static string ReferenceScript(string scriptFile) { var filePath = VirtualPathUtility.ToAbsolute("~/Scripts/" + scriptFile); return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>"; }
so in your master page you can use:
<%= AppHelper.ReferenceScript("jquery-1.2.6.js") %>
I think the simplest way is to use the following, and it works in views to.
<script type="text/javascript" src="<%=ResolveUrl("~/Scripts/myscript.js") %>"> </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With