在内联javascript中插入c#

本文关键字:插入 javascript | 更新日期: 2023-09-27 17:50:11

是否可以将c#变量插入内联javascript函数中?

我使用razor传递选择框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>
上面的

不起作用。我得到一个"不包含'form'的定义"错误。

在内联javascript中插入c#

试试这个

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;
 });
});