![](/img/trans.png)
[英]It's possible mix Javascript and C# code in a DOM event in Blazor?
[英]How to mix C# with javascript for changing html?
我正在嘗試更改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>
編輯:
說明:編譯服務於此請求所需的資源期間發生錯誤。 請查看以下特定的錯誤詳細信息,並適當地修改您的源代碼。
編譯器錯誤消息:CS0103:當前上下文中不存在名稱“ selectValue”
源錯誤: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
。
嘗試使用剃須刀<text>
偽元素另請參見此處
function Kenmerk1() {
var myselect = document.getElementById("kenmerk1");
var selectValue = myselect.options[myselect.selectedIndex].value;
var newOptionsInHtmlStyle = "";
@foreach (var def in ViewBag.Definities) {
<text>
//@def.kenmerk is C# && selectValue is JS;
if(@(def.Kenmerk) == selectValue){
newOptions = newOptions + '<option value="@(def.Variabel)"> @(def.Variabel) </option>';
}
</text>
}
document.getElementById("var1").innerHTML = newOptions;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.