how to embed javascript in Asp.net MVC view - javascript

How can I insert javascript in asp.net MVC application(view)?
I am doing following things in my javascript:
1) Read values from DOM elements.
2) Send data to Controler action method from Jquery Ajax.
3) Validating my input.
4) Read/Write cookies
How can I insert javascript in View.
Should it be something like this?
<script src="../Scripts/Jquery-2.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script>
$(document).ready(function ()
{
$.cookie("pc", "Navada, US");
}
);
</script>
#{
ViewBag.Title = "ViewPage1";
}
<h2>ViewPage1</h2>
Thanks for your answer

Not sure if i understand your question right, but if so you may need to put your script tags into the head tag.
To be able to put your custom js things into head you could try looking at this example:
In your _Layout page add this between <head></head>:
#RenderSection("CustomScripts", required: false);
And on your page:
#section CustomScripts
{
<script src="#Url.Content("~/Scripts/foo.js")" type="text/javascript"></script>
}
EDIT: as #Liam correctly pointed out that the _Layout file could be in any other path, #StephenMuecke's clarification applied.

Related

execute javascript function from controller in MVC 3

I got an action result inside a controller and i need to display Modals from bootstrap-modal the problem is... .
ScriptManager.RegisterStartupScript isn't working like in old asp.net
there is a solution to this? I'm new to mvc.
Ok, the easiest solution for registering javascript from the controller was quite obvious, but frustrating for someone who's new to the pattern:
Using named sections we find a place for put the javascript
You can use [Named Sections][1].
_Layout.cshtml
<head>
<script type="text/javascript" src="#Url.Content("/Scripts/jquery-1.6.2.min.js)">
#RenderSection("JavaScript", required: false)
</head>
and this code for the view
_SomeView.cshtml
#section JavaScript
{
#Html.Raw(ViewBag.message)
}
and in the controller we return
ViewBag.message = #"<script type='text/javascript' language='javascript'>alert(""Hello World!"")</script>"; ;
In ASP.NET MVC scripts are not registered in controller actions. There's a separation between controllers and views. So you could directly put the script in the corresponding view:

Is there a way to append code to an asp.mvc section

I have partials that get rendered as part of a complex page composition.
Some of these partials need some jQuery OnDocumentReady goodness to seed list data etc.
There can be many of these partials chosen during a render (it's very dynamic)
in my _Layout I have a section definition that looks like this
<script src="http://my/fav/cdn/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($) {
#RenderSection("OnDocumentReadySection", false)
});
</script>
in my partials I want to write something like this
#section OnDocumentReadySection{
$('#partial-1').init();
}
and have the result of the page render end up with something like this
<script src="http://my/fav/cdn/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($) {
$('#partial-1').init();
$('#partial-2').init();
$('#partial-3').init();
$('#partial-n').init();
});
</script>
This is to make sure all my javascript is at the bottom of the rendered html which I am told is far more optimal.
Instead of:
jQuery(function($) {
$('#partial-1').init();
$('#partial-2').init();
$('#partial-3').init();
$('#partial-n').init();
});
You should instead assign each of them a common css class (even if you don't define a definition for it) and then do this in the head:
jQuery(function($) {
$('.classname').init();
});
Or if need be:
jQuery(function($) {
$('.classname').each(function(){ $(this).init(); });
});

Jquery validation with zip codes

I have a program that allows a user to enter a zip code to generate a google map. I want to make sure that the zip code is valid. To do so I am using the jquery validate method. Here is how my code looks:
$('#zipInput').validator({
format: 'zipUS',
invalidEmpty: true,
correct: function () {
//Code for correct
},
error: function() {
//Error code here
}
});
The problem is that this is not working for me. I get the error $('#zipInput').validator if not a function. I have been looking for examples of the validate method online and I used this link to build my code. I have added jquery.validate.js to my web page as well (issue with incorrect sources maybe?) Any suggestions or examples that I could look at to help figure out my issue?
EDIT: Here is all of the scripts I use in order:
<script src="jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery.jscrollpane.min.js"></script>
<script src="mwheelIntent.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="Default.js" type="text/javascript"></script>
You need to do at least two things:
Load jQuery itself before the plugin.
Enclose your code in a jQuery.ready() construct.
If you are already doing so, please post all the relevant code.
You have to put a call to the validator code you've written inside the function which you are using to call the dialog. This is if the validator code is in the dialog which you are loading.
Another idea is to put the validator code inside the jquery.ready function in the form from which you load the dialog, but this will add some redundant code to that page.

MVC partial views and Unobtrusive jQuery/Javascript

I'm struggling to work out how I should be authoring my partial views which use jQuery.
For example, in the partial view below, I am displaying a text box which is hooked up to the jquery autocomplete plugin.
Eventually I want the results to be shown with an "X" next to them which the user can then remove, but for the purpose of this example the selected text is simply appended to the sibling div.
Is my jQuery code OK sitting here in the partial view, or should I be putting it in an external file? If an external file is used, then another developer using the partial view will need to be aware that the external js file should be included - is that OK?
I suppose my question really is that, although I'm kind of OK with jQuery (finding elements in the DOM, calling actions asynchronously etc..), I need some sort of guidance on where to put all this code that will stop me getting in a mess.
Does any of what I have just typed make sense????
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".acEmployee").autocomplete({
source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"],
select: function(event, ui) {
$(this).siblings().append(ui.item.value);
}
});
});
</script>
<div><div></div><input class="acEmployee" /></div>
If the JavaScript is "hookup" code then I don't mind it being in with the partial - as after all, everything it relates to is there.
If the JavaScript is "framework" code and can be reused all over the place, and isn't dependant on anything in the partial then I put it in its own file.
That's just what I do, but I'd be interested in hearing other peoples methods too.
If possible, keep all your js code in an external js files. That way you can put your jquery includes at the bottom of the page.
for .net mvc try something like:
<!--try fetching jquery from CDN, if CDN is down, fallback to local-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='<%:Url.Content("~/Scripts/jquery-1.5.1.min.js")%>' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" language="javascript">
var MVC_baseurl = "<%:Url.Content("~/") %>";
</script>
<script type="text/javascript" language="javascript" src="<%:Url.Content("~/Scripts/jquery-ui-1.8.10.custom.min.js")%>"></script>
<script type="text/javascript" language="javascript" src="<%:Url.Content("~/Scripts/plugins.js")%>"></script>
<asp:ContentPlaceHolder ID="BottomJavascript" runat="server">
</asp:ContentPlaceHolder>
You can then put your page-specific stuff in the content placeholders. , your master page specific plugins in plugins.js, and you can use
var path = MVC_baseurl + "Controller/Action"
and use that in your ajax calls etc...

ASP.NET MVC jQuery autocomplete with url.action helper in a script included in a page

I have been building my first ASP.NET MVC web app. I have been using the jQuery autocomplete widget in a number of places like this:
<head>
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
</head>
The thing is I have this jQuery code in a number of different places through my web app. So i thought I would create a seperate javascript script (script.js) where I could put this code and then just include it in the master page. Then i can put all these repeated pieces of code in that script and just call them where I need too. So I did this. My code is shown below:
In the site.js script I put this function:
function doAutoComplete() {
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
}
On the page I have:
<head>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
doAutoComplete();
</script>
</head>
But when I do this I get an Invalid Argument exception and the autocomplete doesnt work. What am I doing wrong? Any ideas?Do i need to pass something to the doAutoComplete function?
The <%= will not be evaluated in your external javascript.
Solution: pass the URL as a parameter to your javascript function.
<script>
doAutoComplete('<%= Url.Action("Model", "AutoComplete") %>');
</script>
function doAutoComplete(url) {
$("#model").autocomplete({ source: url });
}
You need to put the function call in a script block, and make sure jquery is loaded before your site.js ...
<head>
<script src='path/to/jquery.js'></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script>
doAutoComplete();
</script>
</head>
EDIT:
Maybe the '<%= ... =%>' tag isn't being evaluated server-side, before the function gets sent to the browser? Here is an article on this: http://www.west-wind.com/weblog/posts/252178.aspx
Here is a quote from the post:
There's also a problem if you need
access to the [ASP.NET] variables in
.js files - you can't embed script
tags into a .js file so getting a
dynamic value into a static file is
problematic

Categories