最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Razor button onclick call only when condition is true - Stack Overflow

programmeradmin1浏览0评论

Is it possible to call onclick event on button only when certain condition is met ?

F.e.: I would like to call my onclick event if function call returns number > 0, something like: if(checkNoOfRows() > 0) //call onclickevent

Is it possible to do this inline ?

Here's my button onclick event, which I would like to call only when certain condition is fulfilled:

<button id="btnExportXLSPropsChild" onclick="location.href='@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })'">Export</button>

Is it possible to call onclick event on button only when certain condition is met ?

F.e.: I would like to call my onclick event if function call returns number > 0, something like: if(checkNoOfRows() > 0) //call onclickevent

Is it possible to do this inline ?

Here's my button onclick event, which I would like to call only when certain condition is fulfilled:

<button id="btnExportXLSPropsChild" onclick="location.href='@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })'">Export</button>
Share Improve this question asked Oct 6, 2015 at 16:06 FrenkyBFrenkyB 7,22717 gold badges74 silver badges125 bronze badges 2
  • Do you want to do the check on the server or the client? – James Brierley Commented Oct 6, 2015 at 16:11
  • I want to do the check on the client. – FrenkyB Commented Oct 6, 2015 at 16:18
Add a ment  | 

3 Answers 3

Reset to default 3

You can do this check in razor, but the syntax is a bit messy. You need the <text> elements so that it doesn't try to parse your onclick as code on the server:

<div @if (true) { <text>onclick="test"</text>  }></div>

However, a better approach would probably be to add the url as an attribute and then bind an event in javascript with the check. Your template will then be something like:

<button id="btnExportXLSPropsChild" data-url="@Url.Action("exportUserProp", "UserManagement", new { typeToExport = "CHILD" })">Export</button>

And then in the javascript with jQuery:

$("#btnExportXLSPropsChild").on('click', function(){
    if(checkNumberOfRows() > 0){
        var url = $(this).data('url');
        window.location.href = url;
    }
}

You should remove the inline event and use an event handler instead. From the JavaScript event handler, you can check how many rows exist and conditionally run your function.

$("#btnExportXLSPropsChild").on('click', function(){
    if(checkNumberOfRows() > 0){
        //code goes here
    }
}

Jquery can do the magic for you :

$('button').click(function(){ if(condition > 0) { windown.location.href = '@Url.Action("Action","Controller")'; } });

发布评论

评论列表(0)

  1. 暂无评论