基于jquery hasClass输出将参数传递给@Url.Action

Passing parameter to @Url.Action based on jquery hasClass output

我正在尝试根据 jquery 的 hasClass 输出将整数参数传递给 Url.Action。类似下面但语法无效。

<li class="myClass">
    <a href="@Url.Action("SetActionMode", "Home",  new { enable = $(this).find('i').hasClass("fa-check") ? 0 : 1 })">
      <i class="fa fa-check"></i> Debug Mode
    </a>
</li>

上面的正确语法是什么,或者有什么简单的方法可以做到这一点?

ASP.NET 需要来自 jQuery 的值,但是两者不会同时 运行 - jQuery 在客户端上是 运行在服务器端,ASP.NET 是 运行。因此,在服务器端,它编译并将其发送到客户端,然后在客户端,它 运行 是 jQuery 代码。 hasClass 是 jQuery 代码,new { ... 是 ASP.NET 代码,这就是语法不正确的原因。

你不能这样做,但你有另一种选择,即给你的锚标签一个class,然后为此编写一个点击功能,在此之后使用location.href执行相同的操作:

<li class="myClass">
    <a href="javascript:void(0)" class="clickme">
      <i class="fa fa-check"></i> Debug Mode
    </a>
</li>

<script>
$('.clickme').on('click',function(){
location.href='/Home/SetActionMode?enable='+$(this).find('i').hasClass('fa-check')?0:1;
})
</script>

这一定能满足您的需求。

我会说你应该 'interrupt' link 单击,构建 URL 然后转到此 URL。

$(".myClass a").click(function(event) {
    event.preventDefault();
    var url = $(this).attr('href');
    // here you do whatever makes sense
    url = url + "?enable=" + ($(this).find('i').hasClass("fa-check") ? 0 : 1)
    window.location.href = url;

});