如何使用JavaScript或jQuery在MVC4中单击添加按钮时将数据插入表中?

时间:2015-11-04 05:15:08

标签: javascript jquery asp.net-mvc

我正在尝试使用jQuery将记录添加到表中。示例代码如下。



@section scripts

{
    
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
 
 type="text/css" />
    <script>
        //Date Picker
        $(function ()
        {
            $('#orderDate').datepicker({ dateFormat: 'mm-dd-yy' })
        });

        $(document).ready(function () {
            var orderItems = [];
            // Add Button Click Function
            $('#add').click(function () {

                //Check Validation Of OrderItems
                var isValidItem =false;
                if ($('#itemName').val().trim()=='')
                {
                    $('#itemName').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else
                {
                    $('#itemName').siblings('span.error').css('visibility','hidden');                
                }

                if(! ($('#quantity').val().trim() != '' && ! isNaN($('#quantity').val().trim())))
                {
                    $('#quantity').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else {
                    $('#quantity').siblings('span.error').css('visibility','hidden');
                }

                if(! ($('#rate').val().trim() != '' && ! isNaN($('#rate').val().trim())))
                {
                    $('#rate').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else {
                    $('#rate').siblings('span.error').css('visibility','hidden');
                }



        //add Item To List If Valid
                 If(isValidItem)
                 {
                     OrderItems.push(
                         {
                             ItemName: $('#itemName').val().trim(),
                             Quantity: parseInt($('#quantity').val().trim()),
                             Rate    : parseFloat($('rate').val().trim()),
                             Total   : parseInt($('#quantity').val().trim()) *  parseFloat($('rate').val().trim())
                         });
                     $('#itemName').val('').focus();
                     $('#quantity').val('');
                     $('#rate').val('');

                 }
                 GenratedItemTable();

});

            // Save Button Click Function 
            $('#submit').click(function() {
                //Validation of  Order 

                var IsAllValid=true;
                if (OrderItems.length == 0)
                {
                    $ ('#orderItems').html('<span type="color:red;"> please add order items </span>');
                    isAllVaild=false;
                }

                if( $('#orderNo').val().trim() == '')
                {
                    $('#orderNo').siblings('span.error').css('Visibility','visible');
                    isAllVaild=false;
                }
                else
                {
                    $('#orderDate').siblings('span.error').css('Visibility','hidden');
                }

                if( $('#orderDate').val().trim() == '')
                {
                    $('#orderDate').siblings('span.error').css('Visibility','visible');
                    isAllVaild=false;
                }
                else
                {
                    $('#orderDate').siblings('span.error').css('Visibility','hidden');
                }

                // Save If Valid

                if (isAllVaild)
                {
                    var data={ OrderNo  : $('#orderNo').val().trim(),
                        OrderDate: $('#orderDate').val().trim(),
                        Description :$('#description').val().trim(),
                        OrderItems : orderItems
                    }
                }
                $(this).val('Please Wait....');
                $.ajax({

                    url :' /Home/SaveOrder/',
                    type:"POST",
                    data:JSON.stringify(data),
                    datatype:"JSON",
                    ContentType:"application/json",
                    success :function (d)
                    {
                        //check is successfully save to database 
                        if (d.status == true) 
                        {
                            alert('SuccessFully Done');
                            // Clear Form
                            orderItems=[];
                            $('# orderNo').val('');
                            $('# orderDate').val('');
                            $('# orderItems').empty();
    
                        }
                        else
                        {
                            alert('Failed to Save Data');
                        }
    
                    },
                    error :function()
                    {
                        alert('Error. Please Try Again');
                    }
                });
            
                 
                 
           
                     
                 });

            // Function For Show Added Items in Table
            function GenratedItemTable()
            {
                If(orderItems.length > 0)
                {
                    var $table = $('<table/>');
                    $table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
                    var $tbody = $('<tbody/>');
                    $each(orderItems,function(i,val)
                    {
                        var $row=$('<tr/>');
                        $row.append($('<td/>').html(val.ItemName));
                        $row.append($('<td/>').html(val.Quantity));
                        $row.append($('<td/>').html(val.Rate));
                        $row.append($('<td/>').html(val.Total));
                        $tbody.append($row);
                        
                    });
                    $table.append($tbody);
                    $('#OrderItems').html($table);

                }
            }



        });

    </script>
&#13;
<style>
        /* Adding some Css For good Looks*/
        span.error
        {
            display:block;
            visibility:hidden;
            color:red;
            font-size:90%;
        }

        /* Css For Table*/
        .container td 
        {
            vertical-align:top;
        }

        .tablecontainer table
        {
            width:100%;
            border-collapse:collapse;
            border-top:1px solid red;
            border-right:1px solid  red;
        }

        .tablecontainer th 
        {
            border-bottom:2px solid red ! important;
        }

        .tablecontainer th, .tablecontainer td 
        {
            text-align:left;
            border-left:1px solid  red;
            padding : 5px;
            border-bottom: 1px solid red;

        }
        .ui.widget 
        {
            font-size: 12px !important;    
        }
    </style>
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>Master Details Entry</h2>

<div class ="container" style ="max-width:600px">
   
    <div class ="master">
        <h4>Order Details</h4>
    </div>  
    <table>
        <tr>
            <td> Order No </td>
            <td> 
                <input type="text" id="orderNo" />
                <span class="error">Order No Required</span>
            </td>
            <td>Order Date</td>
            <td>
                <input type="text" id="orderDate" />
                <span class="error">Order Valid OrderDate Required(Ex: MM-DD-YY)</span>
            </td>
        </tr>
        <tr>
            <td>Description</td>
            <td colspan="3">
                <textarea id="description" style="width:100%"></textarea>
            </td>
        </tr>
    </table>

    <div class="Details">
        <h4>Order Items</h4>
        <table width="100%">
            <tr>
                <td>ItemName</td>
                <td>Quantity</td>
                <td>Rate</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <input type="text" id="itemName" />
                    <span class="error">ItemName Required</span>
                </td>
                <td>
                    <input type="text" id="quantity" />
                    <span class ="error ">Valid quantity required</span>
                </td>
                <td>
                    <input type="text" id="rate" />
                    <span class="error">Valid Rate Required</span>
                </td>
                <td>
                    <input type="button" id="add" value="add" />
                </td>
            </tr>
        </table>
 <div id="OrderItems" class="tablecontainer"> 

 </div>
        <div style="padding:10px 0px";text-align="right">
            <input type="submit" type="button" value="save" style="padding:10px 20px" />
        </div>
 </div>
</div>
&#13;
&#13;
&#13;

enter image description here

在我的订单表格中,我有两个类别订单明细和订单商品。如上图所示。

在订单明细中,我有订单号,订单日期,描述

等字段

在订单项目下,我有项目名称数量率等字段,最后我在表格中添加了按钮

如果单击“添加”按钮,则无法将数据保存到DB中的表中。现在我想要的是,如果我点击它想要将数据添加到表中的添加按钮,它也希望在Form中显示为Grid View。对于哪种技术,我必须使用jQuery,JavaScript或任何其他技术?

我尝试使用jQuery:

&#13;
&#13;
@section scripts

{
    
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <


    <script>
        //Date Picker
        $(function ()
        {
            $('#orderDate').datepicker({ dateFormat: 'mm-dd-yy' })
        });

        $(document).ready(function () {
            var orderItems = [];
            // Add Button Click Function
            $('#add').click(function () {

                //Check Validation Of OrderItems
                var isValidItem =false;
                if ($('#itemName').val().trim()=='')
                {
                    $('#itemName').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else
                {
                    $('#itemName').siblings('span.error').css('visibility','hidden');                
                }

                if(! ($('#quantity').val().trim() != '' && ! isNaN($('#quantity').val().trim())))
                {
                    $('#quantity').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else {
                    $('#quantity').siblings('span.error').css('visibility','hidden');
                }

                if(! ($('#rate').val().trim() != '' && ! isNaN($('#rate').val().trim())))
                {
                    $('#rate').siblings('span.error').css('visibility','visible');
                    isValidItem=false;
                }
                else {
                    $('#rate').siblings('span.error').css('visibility','hidden');
                }



        //add Item To List If Valid
                 If(isValidItem)
                 {
                     OrderItems.push(
                         {
                             ItemName: $('#itemName').val().trim(),
                             Quantity: parseInt($('#quantity').val().trim()),
                             Rate    : parseFloat($('rate').val().trim()),
                             Total   : parseInt($('#quantity').val().trim()) *  parseFloat($('rate').val().trim())
                         });
                     $('#itemName').val('').focus();
                     $('#quantity').val('');
                     $('#rate').val('');

                 }
                 GenratedItemTable(); });// Save Button Click Function 
            $('#submit').click(function() {
                //Validation of  Order 

                var IsAllValid=true;
                if (OrderItems.length == 0)
                {
                    $ ('#orderItems').html('<span type="color:red;"> please add order items </span>');
                    isAllVaild=false;
                }

                if( $('#orderNo').val().trim() == '')
                {
                    $('#orderNo').siblings('span.error').css('Visibility','visible');
                    isAllVaild=false;
                }
                else
                {
                    $('#orderDate').siblings('span.error').css('Visibility','hidden');
                }

                if( $('#orderDate').val().trim() == '')
                {
                    $('#orderDate').siblings('span.error').css('Visibility','visible');
                    isAllVaild=false;
                }
                else
                {
                    $('#orderDate').siblings('span.error').css('Visibility','hidden');
                }

                // Save If Valid

                if (isAllVaild)
                {
                    var data={ OrderNo  : $('#orderNo').val().trim(),
                        OrderDate: $('#orderDate').val().trim(),
                        Description :$('#description').val().trim(),
                        OrderItems : orderItems
                    }
                }
                $(this).val('Please Wait....');
                $.ajax({

                    url :' /Home/SaveOrder/',
                    type:"POST",
                    data:JSON.stringify(data),
                    datatype:"JSON",
                    ContentType:"application/json",
                    success :function (d)
                    {
                        //check is successfully save to database 
                        if (d.status == true) 
                        {
                            alert('SuccessFully Done');
                            // Clear Form
                            orderItems=[];
                            $('# orderNo').val('');
                            $('# orderDate').val('');
                            $('# orderItems').empty();
    
                        }strong text
                        else
                        {
                            alert('Failed to Save Data');
                        }
    
                    },
                    error :function()
                    {
                        alert('Error. Please Try Again');
                    }
                });
            
                 
                 
           
                     
                 });

            // Function For Show Added Items in Table
            function GenratedItemTable()
            {
                If(orderItems.length > 0)
                {
                    var $table = $('<table/>');
                    $table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
                    var $tbody = $('<tbody/>');
                    $each(orderItems,function(i,val)
                    {
                        var $row=$('<tr/>');
                        $row.append($('<td/>').html(val.ItemName));
                        $row.append($('<td/>').html(val.Quantity));
                        $row.append($('<td/>').html(val.Rate));
                        $row.append($('<td/>').html(val.Total));
                        $tbody.append($row);
                        
                    });
                    $table.append($tbody);
                    $('#OrderItems').html($table);

                }
            }



        });

    </script> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您的代码现在正在运行。您错过了许多功能,并且没有使用正确的变量或数组。我修复了所有代码,现在它正在运行..

&#13;
&#13;
//Date Picker
$(function() {
  $('#orderDate').datepicker({
    dateFormat: 'mm-dd-yy'
  });
});

$(document).ready(function() {
  var orderItems = [];

  // Add Button Click Function
  $('#add').click(function() {

    //Check Validation Of OrderItems
    var isValidItem = true;
    if ($('#itemName').val().trim() == '') {
      $('#itemName').siblings('span.error').css('visibility', 'visible');
      isValidItem = false;
    } else {
      $('#itemName').siblings('span.error').css('visibility', 'hidden');
    }

    if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
      $('#quantity').siblings('span.error').css('visibility', 'visible');
      isValidItem = false;
    } else {
      $('#quantity').siblings('span.error').css('visibility', 'hidden');
    }

    if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
      $('#rate').siblings('span.error').css('visibility', 'visible');
      isValidItem = false;
    } else {
      $('#rate').siblings('span.error').css('visibility', 'hidden');
    }

    //add Item To List If Valid
    if (isValidItem) {
      var itemName = $('#itemName').val().trim();
      var quantity = parseInt($('#quantity').val());
      var rate = parseInt($('#rate').val());
      var total = parseFloat(quantity * rate).toFixed(2);

      orderItems.push({
        ItemName: itemName,
        Quantity: quantity,
        Rate: rate,
        Total: total
      });

      $('#itemName').val('').focus();
      $('#quantity').val('');
      $('#rate').val('');
    }
    GenratedItemTable();
  });

  // Save Button Click Function 
  $('#submit').click(function() {
    //Validation of  Order 

    var IsAllValid = true;
    if (OrderItems.length == 0) {
      $('#orderItems').html('<span type="color:red;"> please add order items </span>');
      isAllVaild = false;
    }

    if ($('#orderNo').val().trim() == '') {
      $('#orderNo').siblings('span.error').css('Visibility', 'visible');
      isAllVaild = false;
    } else {
      $('#orderDate').siblings('span.error').css('Visibility', 'hidden');
    }

    if ($('#orderDate').val().trim() == '') {
      $('#orderDate').siblings('span.error').css('Visibility', 'visible');
      isAllVaild = false;
    } else {
      $('#orderDate').siblings('span.error').css('Visibility', 'hidden');
    }

    // Save If Valid

    if (isAllVaild) {
      var data = {
        OrderNo: $('#orderNo').val().trim(),
        OrderDate: $('#orderDate').val().trim(),
        Description: $('#description').val().trim(),
        OrderItems: orderItems
      }
    }

    $(this).val('Please Wait....');
    $.ajax({
      url: ' /Home/SaveOrder/',
      type: "POST",
      data: JSON.stringify(data),
      datatype: "JSON",
      ContentType: "application/json",
      success: function(d) {
        //check is successfully save to database 
        if (d.status == true) {
          alert('SuccessFully Done');
          // Clear Form
          orderItems = [];
          $('# orderNo').val('');
          $('# orderDate').val('');
          $('# orderItems').empty();

        } else {
          alert('Failed to Save Data');
        }
      },
      error: function() {
        alert('Error. Please Try Again');
      }
    });
  });

  // Function For Show Added Items in Table
  function GenratedItemTable() {
    if (orderItems.length > 0) {
      var $table = $('<table/>');
      $table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
      var $tbody = $('<tbody/>');
      $.each(orderItems, function(i, val) {
        var $row = $('<tr/>');
        $row.append($('<td/>').html(val.ItemName));
        $row.append($('<td/>').html(val.Quantity));
        $row.append($('<td/>').html(val.Rate));
        $row.append($('<td/>').html(val.Total));
        $tbody.append($row);
      });
      $table.append($tbody);
      $('#OrderItems').html($table);
    }
  }
});
&#13;
/* Adding some Css For good Looks*/

span.error {
  display: block;
  visibility: hidden;
  color: red;
  font-size: 90%;
}
/* Css For Table*/

.container td {
  vertical-align: top;
}
.tablecontainer table {
  width: 100%;
  border-collapse: collapse;
  border-top: 1px solid red;
  border-right: 1px solid red;
}
.tablecontainer th {
  border-bottom: 2px solid red ! important;
}
.tablecontainer th,
.tablecontainer td {
  text-align: left;
  border-left: 1px solid red;
  padding: 5px;
  border-bottom: 1px solid red;
}
.ui.widget {
  font-size: 12px !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/i18n/jquery-ui-i18n.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<h2>Master Details Entry</h2>
<div class="container" style="max-width: 600px">
  <div class="master">
    <h4>Order Details</h4>

  </div>
  <table>
    <tr>
      <td>Order No</td>
      <td>
        <input type="text" id="orderNo" />
        <span class="error">Order No Required</span>

      </td>
      <td>Order Date</td>
      <td>
        <input type="text" id="orderDate" />
        <span class="error">Order Valid OrderDate Required(Ex: MM-DD-YY)</span>

      </td>
    </tr>
    <tr>
      <td>Description</td>
      <td colspan="3">
        <textarea id="description" style="width: 100%"></textarea>
      </td>
    </tr>
  </table>
  <div class="Details">
    <h4>Order Items</h4>
    <table width="100%">
      <tr>
        <td>ItemName</td>
        <td>Quantity</td>
        <td>Rate</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>
          <input type="text" id="itemName" />
          <span class="error">ItemName Required</span>
        </td>
        <td>
          <input type="text" id="quantity" />
          <span class="error ">Valid quantity required</span>
        </td>
        <td>
          <input type="text" id="rate" />
          <span class="error">Valid Rate Required</span>
        </td>
        <td>
          <input type="button" id="add" value="add" />
        </td>
      </tr>
    </table>
    <div id="OrderItems" class="tablecontainer"></div>
    <div style="padding: 10px 0px; text-align: right">
      <input type="button" value="save" style="padding: 10px 20px" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的逻辑存在严重问题

           $(document).ready(function () {
      var itm = [];
      // Add Button Click Function
      $('#add').click(function () {

          var i = 0;
          if ($('#itemName').val() == '') {
              $('#itemName').siblings('span.error').css('visibility', 'visible');
          } else {
              $('#itemName').siblings('span.error').css('visibility', 'hidden');
              i++;
          }

          if ($('#quantity').val() == '' || isNaN($('#quantity').val())) {
              $('#quantity').siblings('span.error').css('visibility', 'visible');

          } else {
              $('#quantity').siblings('span.error').css('visibility', 'hidden');
              i++;
          }

          if ($('#rate').val() == '' || isNaN($('#rate').val())) {
              $('#rate').siblings('span.error').css('visibility', 'visible');
          } else {
              $('#rate').siblings('span.error').css('visibility', 'hidden');
              i++;
          }
          if (i == 3) {
              itm.push({
                  ItemName: $('#itemName').val(),
                  Quantity: parseInt($('#quantity').val()),
                  Rate: parseFloat($('#rate').val()),
                  Total: parseInt($('#quantity').val()) * parseFloat($('#rate').val())
              });
              $('#itemName').val('').focus();
              $('#quantity').val('');
              $('#rate').val('');

          }
          GenratedItemTable(itm);
      });
      $('input[value="save"]').click(function () {
          $.ajax({

              url: ' /Home/SaveOrder/',
              type: "POST",
              data: JSON.stringify(itm),
              datatype: "JSON",
              ContentType: "application/json",
              success: function (d) {
                  //check is successfully save to database 
                  if (d.status == true) {
                      alert('SuccessFully Done');
                  }
                  else {
                      alert('Failed to Save Data');
                  }

              },
              error: function () {
                  alert('Error. Please Try Again');
              }
          });
      });
      // Function For Show Added Items in Table
      function GenratedItemTable(itm) {
          if (itm.length > 0) {
              var $table = $('<table/>');
              $table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
              var $tbody = $('<tbody/>');
              $.each(itm, function (i, val) {
                  var $row = $('<tr/>');
                  $row.append($('<td/>').html(val.ItemName));
                  $row.append($('<td/>').html(val.Quantity));
                  $row.append($('<td/>').html(val.Rate));
                  $row.append($('<td/>').html(val.Total));
                  $tbody.append($row);

              });
              $table.append($tbody);
              $('#OrderItems').html($table);
          }
      }



  });

jsfiddle:https://jsfiddle.net/0zwo70os/4/