我正在尝试更改 html DOM 元素。使用来自 asp.net 的数据。来自 CSharp 的所有数据都在 ViewBags 中。 ViewBag.Kenmerken 是一个字符串列表,而 ViewBag.Definities 是一个包含变量“variabel”和变量“kenmerk”的定义对象列表。我有以下代码:
@{
ViewBag.Title = "KenmerkSelectie";
}
<script type="text/javascript">
function Kenmerk1() {
var myselect = document.getElementById("kenmerk1");
var selectValue = myselect.options[myselect.selectedIndex].value;
var newOptions= "";
@foreach (var def in ViewBag.Definities) {
//@def.kenmerk is C# && selectValue is JS;
if(@def.Kenmerk == selectValue){
newOpstions= newOptions+ "<option value=\"@def.Variabel\"> @def.Variabel </option>";
}
}
document.getElementById("var1").innerHTML = newOptions;
}
<div class="kenmerk">
<h3>Kenmerk 1</h3>
<select id="kenmerk1" onchange="Kenmerk1()">
@foreach (var item in ViewBag.Kenmerken)
{
<option value="@item">
@item
</option>
}
</select>
<select id="var1" multiple="multiple">
<!-- add option from js function -->
</select>
</div>
编辑:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'selectValue' does not exist in the current context
Source Error: if(@def.Kenmerk == selectValue){
请您参考如下方法:
您没有正确转义您的 " (引述)。这一行:
newOptions = newOptions + "<option value="@def.Variabel"> @def.Variabel </option>";
应该是这样的:
newOptions = newOptions + @"<option value=""@def.Variabel""> @def.Variabel</option>";
不过,对于 ASP.NET MVC 设计原则,我建议不要使用 ViewBag。请改用模型来传递数据。 http://tech.trailmax.info/2013/12/asp-net-mvc-viewbag-is-bad/
编辑: 此外,看起来您应该将数据转换为 JSON,以便您可以在 JavaScript 端比较您的值。自 def.Kenmerk在 C# 中,它将无法计算 JavaScript 变量 selectValue在 == 上比较。
