简体   繁体   English

将C#插入内联JavaScript

[英]Insert c# into inline javascript

Is it possible to insert ac# variable into a inline javascript function? 是否可以将ac#变量插入内联javascript函数?

I'm using razor to pass the select boxes id. 我正在使用剃刀传递选择框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>

The above does not work. 上面的方法不起作用。 I get a "does not contain a definition for 'form'" error. 我收到“不包含“表单”的定义”错误。

试试这个

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

Yes. 是。 You can use Razor syntax in javascript as long as it is in the view file. 您可以在javascript中使用Razor语法,只要它在视图文件中即可。

I prefer to keep the markup clean without the behavior(separation of concern) and keep that behavior in unobtrusive javascript way. 我更喜欢保持标记干净无行为(关注点分离),并以简洁的JavaScript方式保持行为。 I would keep a HTML 5 data attribute to set the value of url3 variable. 我将保留HTML 5 数据属性来设置url3变量的值。

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

and in javascript, listen to the change event of SELECT element with .input class and redirect to the new page 并在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