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

877 Views Asked by At

I am trying to pass an integer parameter to Url.Action based on hasClass output of jquery. something like below but is invalid syntax.

<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>

What is the correct syntax for above or is there some easy way to do this?

3

There are 3 best solutions below

1
On BEST ANSWER

I'd say you should 'interrupt' link clicking, construct URL and then go to this 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;

});
0
On

ASP.NET needs a value from jQuery, however the two don't run at the same time - jQuery is run on the client side, ASP.NET is run on the server side. So, on the server side, it compiles and sends it to the client side, then, on the client side, it runs the jQuery code. The hasClass is jQuery code, the new { ... is ASP.NET code, this is why it's incorrect syntax.

1
On

You cannot do it like this,But you have another option i.e GIve your anchor tag a class, then write a click function for this, After this use location.href to perform the same:

<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>

This will Surely do what you need.