Calling JavaScript function in MVC 5 Razor view

回眸只為那壹抹淺笑 提交于 2019-12-30 06:30:06

问题


I have seen in another post that you can call a JavaScript function in your razor code like so:

@:FunctionName()

For me though this only outputs the actual words 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'? Anyway around this?


回答1:


You need to put your javascript in a <script> tag, and you need to call the functions within their scope:

<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>



回答2:


If you are passing any parameter to the JavaScript function, it must be enclosed with quotes ('').

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


来源:https://stackoverflow.com/questions/26736163/calling-javascript-function-in-mvc-5-razor-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!