Skip to content Skip to sidebar Skip to footer

How To Call Javascript In Mvc3 Pattern

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 AS

Solution 1:

You should remove the <text> tags from your script so that the view looks like this:

<p><divid="map_canvas2"style = "width:100%; height:100%">
        result from Javascript
    </div></p><scripttype="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:

<scripttype="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>

Post a Comment for "How To Call Javascript In Mvc3 Pattern"