Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

@: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?

like image 452
Guerrilla Avatar asked Nov 04 '14 13:11

Guerrilla


2 Answers

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>
like image 160
jrummell Avatar answered Sep 20 '22 07:09

jrummell


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>  
    } 
like image 31
suresh mathan Avatar answered Sep 20 '22 07:09

suresh mathan