在asp.net mvc

时间:2017-10-26 21:44:44

标签: javascript asp.net asp.net-mvc

我正在使用javascript检查表行是否为空。如果它们是空的,它应该给用户一个弹出消息,否则重定向。我一直在尝试这个,但它的作用是给我一个警告信息,不管是否有某些东西。

 <script type="text/javascript">
function onSubmit() {
    var rowCount = $('#myTable tr').length;
    if (rowCount < 0) {

            location.href = '@Url.Action("","")';

        }
        else {

            alert("No item was added");
        }
}

<table id ="myTable">
                    <tr>
                        <th class="col-md-2">Customer Number</th>
                        <th class="col-md-2">Customer Description</th>
                        <th class="col-md-3">Expense Account</th>

                    </tr>
                    @{
                        if (@Model.Customers.Count > 0)

{

foreach (var Customer in @Model.Customers)
                        {
                            <tr>
                                <td class="col-md-2">@Customer.CustomerNumber</td>
                                <td class="col-md-2">@Customer.description</td>
                                <td class="col-md-3">@Customer.expense_account.getDescription</td>

                            </tr>**

    <input type="button" value="Submit" name="Submit" margin="50px" onclick="onSubmit()" class="btn btn-default" />
</div>

2 个答案:

答案 0 :(得分:0)

您的if条件错误!使用当前代码,如果行数零或更多 else part ),则表示您正在显示警报。根据您的问题,您希望在没有行时显示警报,但标题行除外。

因此检查rowcount为1,表示您只有标题行,因此显示错误消息,否则重定向。

function onSubmit() {
    var rowCount = $('#myTable tr').length;
        if (rowCount === 1) {
            alert("No item was added");
         }
        else {
           location.href = '@Url.Action("SomeActionMethod","SomeController")';
        }
 }

您可以专门检查表体中的行数并检查计数为0

function onSubmit() {
    var rowCount = $('#myTable >tbody >tr').length;
        if (rowCount ===0) {
            alert("No item was added");
         }
        else {
           location.href = '@Url.Action("SomeActionMethod","SomeController")';
        }
 }

答案 1 :(得分:0)

  

试试这希望它会起作用

function onSubmit() {
    var rowCount = $('#myTable tr').length-1;
        if (rowCount ==0) {
            alert("No item was added");
         }
        else {
           location.href = '@Url.Action("","")';
        }
 }