I have two tables, Sale and SDetail, which is 1 to many relationship. I am trying to add values to both tables in single view using Ajax JQuery.
even though view is generated perfectly, button click is not triggering when i click add button.
I foung this ajax code from other website as I am new to this.
so Please somebody help me out with this to solve this asap.
here are my controller class create action method,
private SchoolContext db = new SchoolContext();
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "ID", "FullName");
ViewBag.UserID = new SelectList(db.Users, "ID", "FName");
return View();
}
// POST: /Sale/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create( Sale sale)
{
try {
ViewBag.CustomerID = new SelectList(db.Customers, "ID", "FullName", sale.CustomerID);
ViewBag.UserID = new SelectList(db.Users, "ID", "FName", sale.UserID);
if (ModelState.IsValid)
{
// If sales main has SalesID then we can understand we have existing sales Information
// So we need to Perform Update Operation
// Perform Update
if (sale.ID > 0)
{
var CurrentSDetail = db.SDetails.Where(p => p.SaleID == sale.ID);
foreach (SDetail ss in CurrentSDetail)
db.SDetails.Remove(ss);
foreach (SDetail ss in sale.SDetails)
db.SDetails.Add(ss);
db.Entry(sale).State = EntityState.Modified;
}
//Perform Save
else
{
db.Sales.Add(sale);
}
db.SaveChanges();
// If Sucess== 1 then Save/Update Successfull else there it has Exception
return Json(new { Success = 1, SalesID = sale.ID, ex = "" });
}
}
catch (Exception ex)
{
// If Sucess== 0 then Unable to perform Save/Update Operation and send Exception to View as JSON
return Json(new { Success = 0, ex = ex.Message.ToString() });
}
return Json(new { Success = 0, ex = new Exception("Unable to save").Message.ToString() });
}
And my Create view file as follows,
@model ICSTIASHJ.Models.Sale
@*This is for jquery*@
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
@*This is for jquery UI, for Calender control*@
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
@*This is for JSON*@
<script src="../../Scripts/json2.js" type="text/javascript"></script>
@*These are for DataTables*@
<script src="../../Scripts/DataTables-1.8.1/media/js/jquery.dataTables.js" type="text/javascript"></script>
<script src="../../Scripts/DataTables-1.8.1/extras/TableTools/media/js/TableTools.js" type="text/javascript"></script>
<script src="../../Scripts/DataTables-1.8.1/extras/TableTools/media/js/ZeroClipboard.js" type="text/javascript"></script>
@*These are for styling Control*@
<link href="../../Content/DataTables-1.8.1/extras/TableTools/media/css/TableTools.css" rel="stylesheet" type="text/css" />
<link href="../../Content/DataTables-1.8.1/extras/TableTools/media/css/TableTools_JUI.css" rel="stylesheet" type="text/css" />
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
//here i have used datatables.js (jQuery Data Table)
$('.tbl').dataTable({
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"aButtons": [],
"sRowSelect": "single"
},
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": false
});
$('#SDate').datepicker();
var oTable = $('.tbl').dataTable();
});
// Adding new row to Table
// The following code shows how to read from text boxes and then add them to a DataTable.
function Add() {
// Adding item to table
$('.tbl').dataTable().fnAddData([$('#ProductID').val(), $('#Size').val(), $('#Quantity').val(), $('#UnitPrice').val(), $('#Total').val()]);
// Making Editable text empty
$('#ProductID').val("")
$('#Size').val("")
$('#Quantity').val("")
$('#UnitPrice').val("")
$('#Total').val("")
}
// Delete selected row from Table
// Following code shows how to remove a selected item from a DataTable.
// This function is used fro
// delete selected row from Detail Table|
// set deleted item to Edit text Boxes
function DeleteRow() {
// Here I have used DataTables.TableTools plugin for getting selected row items
var oTT = TableTools.fnGetInstance('tbl'); // Get Table instance
var sRow = oTT.fnGetSelected(); // Get Selected Item From Table
// Set deleted row item to editable text boxes
$('#ProductID').val($.trim(sRow[0].cells[0].innerHTML.toString()));
$('#Size').val(jQuery.trim(sRow[0].cells[1].innerHTML.toString()));
$('#Quantity').val($.trim(sRow[0].cells[2].innerHTML.toString()));
$('#UnitPrice').val($.trim(sRow[0].cells[2].innerHTML.toString()));
$('#Total').val($.trim(sRow[0].cells[2].innerHTML.toString()));
$('.tbl').dataTable().fnDeleteRow(sRow[0]);
}
// Save/Posting Data to sales Controller
// Here we have two steps:
// Read view data and create JSON object
// Ajax post
function Sales_save() {
// Step 1: Read View Data and Create JSON Object
// Creating SalesSub Json Object
var SDetail = { "SaleID": "", "ProductID": "", "Size": "", "Quantity": "", "UnitPrice": "", "Total": "" };
// Creating SalesMain Json Object
var Sale = { "ID": "", "SaleInvoiceNo": "", "AccntInvoiceNo": "", "SDate": "", "SubTotal": "", "Discount": "", "NetAmount": "", "PaymentID": "", "CustomerID": "", "UserID": "", "SalesSubs": [] };
// Set Sales Main Value
Sale.ID = $("ID").val();
Sale.SaleInvoiceNo = $("#SaleInvoiceNo").val();
Sale.AccntInvoiceNo = $("#AccntInvoiceNo").val();
Sale.SDate = $("#SDate").val();
Sale.SubTotal = $("SubTotal").val();
Sale.Discount = $("#Discount").val();
Sale.NetAmount = $("#NetAmount").val();
Sale.PaymentID = $("#PaymentID").val();
Sale.CustomerID = $("#CustomerID").val();
Sale.UserID = $("#UserID").val();
// Getting Table Data from where we will fetch Sales Sub Record
var oTable = $('.tbl').dataTable().fnGetData();
for (var i = 0; i < oTable.length; i++) {
// IF This view is for edit then it will read SalesId from Hidden field
if ($('h2').text() == "Edit") {
SDetail.SaleID = $('#ID').val();
}
else {
SDetail.SaleID = 0;
}
// Set SalesSub individual Value
SDetail.ProductID = oTable[i][0];
SDetail.Size = oTable[i][1];
SDetail.Quantity = oTable[i][2];
SDetail.UnitPrice = oTable[i][3];
SDetail.Total = oTable[i][4];
// adding to SalesMain.SalesSub List Item
Sale.SDetail.push(SDetail);
SDetail = { "SaleID": "", "ProductID": "", "Size": "", "Quantity": "", "UnitPrice": "", "Total": "" };
}
// Step 1: Ends Here
// Set 2: Ajax Post
// Here i have used ajax post for saving/updating information
$.ajax({
url: '/Sale/Create',
data: JSON.stringify(Sale),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
if (result.Success == "1") {
window.location.href = "/Sale/index";
}
else {
alert(result.ex);
}
}
});
}
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>SalesMain</legend>
@if (Model != null)
{
<input type="hidden" id="ID" name="SalesId" value="@Model.ID" />
}
<div class="form-horizontal">
<h4>Sale</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.SaleInvoiceNo, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SaleInvoiceNo)
@Html.ValidationMessageFor(model => model.SaleInvoiceNo)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.AccntInvoiceNo, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.AccntInvoiceNo)
@Html.ValidationMessageFor(model => model.AccntInvoiceNo)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SDate)
@Html.ValidationMessageFor(model => model.SDate)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SubTotal, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SubTotal)
@Html.ValidationMessageFor(model => model.SubTotal)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Discount, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Discount)
@Html.ValidationMessageFor(model => model.Discount)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.NetAmount, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.NetAmount)
@Html.ValidationMessageFor(model => model.NetAmount)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CustomerID, "CustomerID", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CustomerID", String.Empty)
@Html.ValidationMessageFor(model => model.CustomerID)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UserID, "UserID", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("UserID", String.Empty)
@Html.ValidationMessageFor(model => model.UserID)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</fieldset>
<br />
<fieldset>
<legend>Add Item</legend>
<div class="row">
<div class="form-group">
<div class="col-md-2"> <label>Product Name :</label> </div>
<div class="col-md-2"> @Html.TextBox("ProductID") </div>
</div>
<div class="form-group">
<div class="col-md-2"> <label>Size :</label> </div>
<div class="col-md-2"> @Html.TextBox("Size") </div>
</div>
<div class="form-group">
<div class="col-md-2"> <label>Quantity :</label> </div>
<div class="col-md-2"> @Html.TextBox("Quantity") </div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-2"> <label>UnitPrice :</label> </div>
<div class="col-md-2"> @Html.TextBox("UnitPrice") </div>
</div>
<div class="form-group">
<div class="col-md-2"> <label>Total :</label> </div>
<div class="col-md-2"> @Html.TextBox("Total") </div>
</div>
<div class="col-md-2 col-md-offset-2">
<input type="button" value="Add" onclick="Add()" />
</div>
</div>
<br />
<br />
<table class=" table table-striped" id="tbl">
<thead>
<tr>
<th> Product Name</th>
<th> size</th>
<th> Quantity</th>
<th> Unit Price</th>
<th> Total</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
foreach (var item in Model.SDetails)
{
<tr>
<td> @Html.EditorFor(i => item.product)</td>
<td> @Html.DisplayTextFor(i => item.Size)</td>
<td> @Html.DisplayTextFor(i => item.Quantity)</td>
<td> @Html.DisplayTextFor(i => item.UnitPrice)</td>
<td> @Html.DisplayTextFor(i => item.Total)</td>
</tr>
}
}
</tbody>
</table>
<br />
<div>
<input type="button" value="Delete Selected Row" onclick="DeleteRow()" />
</div>
</fieldset>
<br />
<div>
<input type="button" value="Sales Save" onclick="Sales_save()" />
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}