簡體   English   中英

將C#插入內聯JavaScript

[英]Insert c# into inline javascript

是否可以將ac#變量插入內聯javascript函數?

我正在使用剃刀傳遞選擇框ID。

<select id="@itemid" style="float:right" class="input" onchange="window.location.href='@url3' + 'booking/' + '?d=' + 'this.form.@itemid.options[this.form.@itemid.selectedIndex].value">
</select>

上面的方法不起作用。 我收到“不包含“表單”的定義”錯誤。

試試這個

onchange='@("string.format("window.location.href='{0}' + 'booking/' + '?d=' + 'this.form.{1}.options[this.form.{1}.selectedIndex].value", @url3, @itemid))'

是。 您可以在javascript中使用Razor語法,只要它在視圖文件中即可。

我更喜歡保持標記干凈無行為(關注點分離),並以簡潔的JavaScript方式保持行為。 我將保留HTML 5 數據屬性來設置url3變量的值。

<select id="@itemid" style="float:right" class="input" data-targeturl="@url3">
</select>

並在javascript中,使用.input類偵聽SELECT元素的change事件,然后重定向到新頁面

$(function(){

 $("SELECT.input").change(function(e){
   var _this=$(this);
   var newUrl=_this.data("targeturl")+"/booking?d="+_this.val();
   window.location.href=newUrl;
 });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM