How to call javascript in MVC3 pattern

2019-07-24 10:46发布

问题:

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

  1. I create a new ASP MVC3 Solution (using Razor)
  2. Add a new JavaScript in Script folder
  3. Add a simple script function in the new JavaScript file, like this:

    function HolaMundo(){
    return "hola desde javascript";
    }
    
  4. 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>
    }
    
  5. 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.

回答1:

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>