Calling JavaScript function in MVC 5 Razor view
74,267
Solution 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>
Solution 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>
}
Author by
Guerrilla
Updated on July 09, 2022Comments
-
Guerrilla almost 2 years
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?
-
Guerrilla over 9 yearsThanks. Is the "@:" syntax a thing? Was it discontinued?
-
Chris Pratt over 9 yearsThe
@:
syntax just tells Razor to treat what follows as plain text. Within the context of a code block, this would be necessary to prevent Razor from attempting to run theFunctionName()
method in a C#/VB context instead of a JavaScript context, where it actually exists. -
jrummell over 9 years@Guerrilla I didn't put this in Visual Studio, so it's possible that you may still need
@:
in front of the javascript function calls. -
Tibrogargan almost 8 yearsYou should use the code formatting options (select the code, Ctrl-k) to make sure that your code is displayed in the manner you intended it to be in your answer. Also, it's better to use something from the question in your example to make it clearer what you mean.
-
d219 almost 5 yearsI believe it will need
@:
in front from what I've just been trying (so@: ShowClarify();
and@: ShowQuote();
)