I'm new to the ASP.NET MVC 3 pattern and I want to call a JavaScript function in view (or controller), to display the result in a div
or span
object.
My solution
- I create a new ASP MVC3 Solution (using Razor)
- Add a new JavaScript in Script folder
Add a simple script function in the new JavaScript file, like this:
function HolaMundo(){
return "hola desde javascript";
}
Add a reference from the JavaScript in the index.csHTML
file from my default controller.
@section JavaScript
{
<script src="@Url.Content("~/Scripts/Maps.Helper.js")" type="text/javascript">
</script>
}
Finally add a call for the function:
<p>
<div id="map_canvas2" style = "width:100%; height:100%">
result from Javascript
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<text>
$('#map_canvas2').text(HolaMundo());
</text>
});
</script>
Result
Doesn't work
So, can any help me? I appreciate your help.
You should remove the <text>
tags from your script so that the view looks like this:
<p>
<div id="map_canvas2" style = "width:100%; height:100%">
result from Javascript
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
$('#map_canvas2').text(HolaMundo());
});
</script>
The <text>
tag is used by the Razor interpreter to indicate a literal value to be rendered as-is without processing. It's useful when you are mixing server side code with client side markup or script. For example:
<script type="text/javascript">
$(document).ready(function() {
@if (Model.IsFooBar)
{
<text>$('#map_canvas2').text(HolaMundo());</text>
}
});
</script>
Also make sure that the section that you have defined in your Index.cshtml
view:
@section JavaScript
{
<script src="@Url.Content("~/Scripts/Maps.Helper.js")" type="text/javascript"></script>
}
you should make sure that is registered in your _Layout.cshtml
somewhere. For example in the <head>
. Also make sure that you have included the jQuery script to your page:
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
@RenderSection("JavaScript")
</head>
...
or even better before the closing </body>
tag which is where it is recommended to place scripts to avoid blocking the browser loading the DOM while fetching them:
...
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
@RenderSection("JavaScript")
</body>
</html>