在一个 C# MVC 项目中,前端设计师给了我一个 View ,其中包含这个小脚本:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (chosenValue == "Planning")
$('#PlanningProcess').show();
if (chosenValue == "Procurement")
$('#ProcurementProcess').show();
if (chosenValue == "Installation")
$('#InstallationProcess').show();
if (chosenValue == "Closure")
$('#ClosureProcess').show();
});
</script>
我想用来自模型的列表替换所有硬编码选项。像这样的事情...
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
// loop over a list from the model here
if (chosenValue == " loop-item-name ")
$('# loop-item-name + Process').show();
// end loop
});
</script>
这可能吗?如果是这样,怎么办?我是否以正确的方式处理这件事?我想我可以使用 razor 语法,但这不起作用。
最佳答案
您无法将 C# 变量与 JS 变量进行比较。但是您可以使用 razor 从 C# 变量创建 JS 变量。
以下是如何用 C# 数组的值填充 JS 数组:
@{
// fetch this from ViewModel if it needs to be dynamic
var cSharpNames = new [] { "Planning", "Procurement"};
}
<script>
var jsNames = []; // this is a JS array
@foreach(var name in cSharpNames) {
<text>jsNames.push(@name);</text>
}
</script>
然后使用 indexOf()
方法在 jsNames 数组中进行搜索,如 Jeremy 所示。
关于javascript - 将静态 JavaScript 函数转换为动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40424607/