简体   繁体   English

在MVC 5 Razor视图中调用JavaScript函数

[英]Calling JavaScript function in MVC 5 Razor view

I have seen in another post that you can call a JavaScript function in your razor code like so: 我在另一篇文章中看到,您可以在剃刀代码中调用JavaScript函数,如下所示:

@:FunctionName()

For me though this only outputs the actual words FunctionName() 对我来说虽然这只输出实际的单词FunctionName()

Here is my view: 这是我的观点:

@model PriceCompare.Models.QuoteModel

@{
    ViewBag.Title = "Quote";
}

<h2>Quote</h2>

@if (@Model.clarify == true)
{
    // do drop down loic
    @:ShowClarify();
}
else
{
    // fill quote
    @:ShowQuote();
}
<div class="clarify">

    You can see the clarify div
</div>
<div class="quote">

    You can see the quote div
</div>

@section head {

    <script type="text/javascript">

        $(document).ready(
            function ShowQuote() {
                $(".quote").show();
            },
            function ShowClarify() {
                $(".clarify").show();
            }
        );

    </script>
}

Is it because I have nested it in an `@if'? 是因为我把它嵌套在`@if'中? Anyway around this? 无论如何围绕这个?

You need to put your javascript in a <script> tag, and you need to call the functions within their scope: 您需要将javascript放在<script>标记中,并且需要调用其范围内的函数:

<script type="text/javascript">

    $(document).ready(
        function ShowQuote() {
            $(".quote").show();
        },
        function ShowClarify() {
            $(".clarify").show();
        }

        @if (@Model.clarify == true)
        {
            // do drop down loic
            ShowClarify();
        }
        else
        {
            // fill quote
            ShowQuote();
        }
    );

</script>

If you are passing any parameter to the JavaScript function, it must be enclosed with quotes (''). 如果要将任何参数传递给JavaScript函数,则必须用引号('')括起来。

foreach (var item in files)
    {
        <script type="text/javascript">
            Attachment(**'@item.FileName'**, **'@item.Size'**);
        </script>  
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM