在 MVC 5 Razor 视图中调用 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26736163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling JavaScript function in MVC 5 Razor view
提问by Guerrilla
I have seen in another post that you can call a JavaScript function in your razor code like so:
我在另一篇文章中看到,您可以像这样在 razor 代码中调用 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'? Anyway around this?
是因为我将它嵌套在`@if' 中吗?无论如何围绕这个?
回答by jrummell
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>
回答by suresh mathan
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>
}

