Jquery ajax函数不会在asp mvc中保存数据库中的数据 [英] Jquery ajax function does not save data in database in asp mvc
本文介绍了Jquery ajax函数不会在asp mvc中保存数据库中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dear All,
Thanks in advance,
I have a JQuery Ajax function which suppose to save data in Database. Unfortunately it gives an error which I could not find out yet. please go through my all codes and tell me where I did the mistake.
in the MasterIndex.cshtml page I am simply passing int data directly (to CustomerId and UserId) because I do not know how to get id value of selected dropdown text which linked to other table. So after solving error I would like to know how to get ID value also.
here is that code;
if (isAllValid) {
var data = {
AccntInvoiceNo: $('#AccountInvNo').val().trim(),
SaleDate: $('#SaleDate').val().trim(),
SubTotal: $('#SubTotal').val().trim(),
Discount: $('#Discount').val().trim(),
NetAmount: $('#NetTotal').val().trim(),
CustomerId: 2,
UserId: 1,
SaleDescs: orderItems
}
这里是其他主要代码
Sale.cs
here are other main codes
Sale.cs
public partial class Sale
{
public Sale()
{
this.Payments = new HashSet<Payment>();
this.SaleDescs = new HashSet<SaleDesc>();
}
public int Id { get; set; }
[Required,Display(Name = "Accounts Invoice No.")]
public string AccntInvoiceNo { get; set; }
[Required,Display(Name = "Date of Sale"), DataType(DataType.Date)]
public System.DateTime SaleDate { get; set; }
[Display(Name = "Sub Total")]
public Nullable<decimal> SubTotal { get; set; }
public Nullable<decimal> Discount { get; set; }
[Required,Display(Name = "Net Amount")]
public decimal NetAmount { get; set; }
[Display(Name = "Customer Name")]
public int CustomerId { get; set; }
[Display(Name = "User")]
public int UserId { get; set; }
public virtual ICollection<Payment> Payments { get; set; }
public virtual Person Person { get; set; }
public virtual User User { get; set; }
public virtual ICollection<SaleDesc> SaleDescs { get; set; }
}
}
SaleDesc.cs
SaleDesc.cs
public partial class SaleDesc
{
public int Id { get; set; }
[Display(Name = "No")]
public int SaleId { get; set; }
[Required,Display(Name = "Name of Product")]
public int ProductId { get; set; }
public string Size { get; set; }
[Required]
public string Quantity { get; set; }
[Required,Display(Name = "Unit Price")]
public Nullable<decimal> UnitPrice { get; set; }
[Required,Display(Name = "Net Amount")]
public decimal NetAmount { get; set; }
public virtual Product Product { get; set; }
public virtual Sale Sale { get; set; }
}
SaleController.cs
SaleController.cs
public class SaleController : Controller
{
private TIASHJDBContext db = new TIASHJDBContext();
public ActionResult MasterIndex()
{
ViewBag.CustomerId = new SelectList(db.Persons, "Id", "FullName");
ViewBag.ProductId = new SelectList(db.Products, "Id", "PName");
return View();
}
//Post action for Save data to database
[HttpPost]
public JsonResult SaveOrder(Sale s)
{
bool status = false;
if (ModelState.IsValid)
{
Sale sale = new Sale { AccntInvoiceNo = s.AccntInvoiceNo, SaleDate = s.SaleDate, SubTotal = s.SubTotal, Discount = s.Discount, NetAmount = s.NetAmount, CustomerId = s.CustomerId, UserId = s.UserId };
foreach (var i in s.SaleDescs)
{
//
// i.TotalAmount =
sale.SaleDescs.Add(i);
}
db.Sales.Add(sale);
db.SaveChanges();
status = true;
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status } };
}
}
MasterIndex.cshtml
MasterIndex.cshtml
@{
ViewBag.Title = "MasterIndex";
}
<h2>Sales Order</h2>
<div class="container">
<div class="master">
<h4>Sale details</h4>
<div class="panel-group">
<div class="panel panel-default">
<div class="table">
<table class="table">
<tr>
<td>Account Invoice No</td>
<td>
<input type="text" id="AccountInvNo" />
<span class="error">Account Invoice No is required</span>
</td>
<td>Sale Date</td>
<td>
<input type="text" id="SaleDate" />
<span class="error">Valid sale date is required (ex. MM-dd-yyyy)</span>
</td>
<td>Customer Name</td>
<td>
@*<input type="text" id="Customer" />*@
@Html.DropDownList("CustomerID", null,String.Empty, new { id = "Customer", @class = "text-field" })
<span class="error">Valid customer name is required</span>
</td>
</tr>
<tr>
<td>Sub Total</td>
<td>
<input type="text" id="SubTotal" readonly="readonly" />
</td>
<td>Discount</td>
<td>
<input type="text" id="Discount" />
</td>
<td>Net Total</td>
<td>
<input type="text" id="NetTotal" readonly="readonly" />
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="details">
<h4>Sale Item Details</h4>
<table class="table table-striped table-hover table-condensed">
<tr>
<td>Item Name</td>
<td>Quantity</td>
<td>Unit Price</td>
<td> </td>
</tr>
<tr>
<td>
@* <input type="text" id="itemName" />*@
@Html.DropDownList("ProductID", null, String.Empty, new { id = "itemName", @class = "text-field" })
<span class="error">Item name is required</span>
</td>
<td>
<input type="text" id="quantity" />
<span class="error">Valid quantity is required</span>
</td>
<td>
<input type="text" id="UnitPrice" />
<span class="error">Valid Unit Price is required</span>
</td>
<td>
<input type="button" class="btn btn-primary" id="add" value="Add" style="padding:10px 30px" />
</td>
</tr>
</table>
<div id="orderItems" class="tablecontainer">
</div>
<div style="padding:10px 0px; text-align:right">
<input id="submit" type="button" value="Save" class="btn btn-success" style="padding:10px 40px" />
</div>
</div>
</div>
</div>
@*JQuery code*@
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
@section Scripts{
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
//Date Picker
$(function () {
$('#SaleDate').datepicker({
dateFormat: 'mm-dd-yy'
});
});
var subTot = 0;
$('#Discount').val(0);
$(document).ready(function () {
var orderItems = [];
//Add button click function
$('#add').click(function () {
//Check validation of order item
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'visible');
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#UnitPrice').val().trim() != '' && !isNaN($('#UnitPrice').val().trim()))) {
isValidItem = false;
$('#UnitPrice').siblings('span.error').css('visibility', 'visible');
}
else {
$('#UnitPrice').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()),
UnitPrice: parseFloat($('#UnitPrice').val().trim()),
SubTotal: parseInt($('#quantity').val().trim()) * parseFloat($('#UnitPrice').val().trim())
});
subTot = subTot + (parseInt($('#quantity').val().trim()) * parseFloat($('#UnitPrice').val().trim()))
//Clear fields
$('#itemName').val('').focus();
$('#quantity,#UnitPrice').val('');
}
//populate order items
GeneratedItemsTable();
$('#SubTotal').val(parseFloat(subTot));
$('#NetTotal').val(parseFloat(subTot) - parseFloat($('#Discount').val().trim()));
});
//Save button click function
$('#submit').click(function () {
//validation of order
var isAllValid = true;
if (orderItems.length == 0) {
$('#orderItems').html('<span style="color:red;">Please add order items</span>');
isAllValid = false;
}
if ($('#AccountInvNo').val().trim() == '') {
$('#AccountInvNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#AccountInvNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#SaleDate').val().trim() == '') {
$('#SaleDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#SaleDate').siblings('span.error').css('visibility', 'hidden');
}
if ($('#Customer').val().trim() == '') {
$('#Customer').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#Customer').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
AccntInvoiceNo: $('#AccountInvNo').val().trim(),
SaleDate: $('#SaleDate').val().trim(),
SubTotal: $('#SubTotal').val().trim(),
Discount: $('#Discount').val().trim(),
NetAmount: $('#NetTotal').val().trim(),
CustomerId: 2,
UserId: 1,
SaleDescs: orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/Sale/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) {
//will send status from server side
alert('Successfully done.');
//clear form
orderItems = [];
$('#AccountInvNo').val('');
$('#saleDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function (exception) {
alert('Exeption:'+exception);
$('#submit').val('Save');
}
});
}
});
//function for show added items in table
function GeneratedItemsTable() {
if (orderItems.length > 0) {
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Unit Price</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.UnitPrice));
$row.append($('<td/>').html(val.SubTotal));
$tbody.append($row);
});
$table.append($tbody);
$('#orderItems').html($table);
}
}
});
</script>
}
<style>
/*Adding some css for looks good*/
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 #BFAEAE;
border-right: 1px solid #BFAEAE;
}
.tablecontainer th {
border-bottom: 2px solid #BFAEAE !important;
}
.tablecontainer th, .tablecontainer td {
text-align: left;
border-left: 1px solid #BFAEAE;
padding: 5px;
border-bottom: 1px solid #BFAEAE;
}
.ui-widget {
font-size: 12px !important;
}
</style>
我尝试过: < br $> b $ b
我试图在crome上调试ajax函数,但无法理解。
错误是[object Object]
What I have tried:
I tried to debug ajax function on crome, but could not understand.
error was "[object Object]"
推荐答案
('#AccountInvNo')。val()。trim(),
SaleDate:
('#AccountInvNo').val().trim(), SaleDate:
('#SaleDate')。val()。trim(),
SubTotal:
('#SaleDate').val().trim(), SubTotal:
('# SubTotal')。val()。trim(),
折扣:
('#SubTotal').val().trim(), Discount:
这篇关于Jquery ajax函数不会在asp mvc中保存数据库中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文