I am new to asp.net mvc. How can I automatically generate new Guid inside of foreach loop? I am using List<Expense>
in view model and GUID as PrimaryKey, how I insert a multiple row from datatable to database insertion?
Here is my view model. I can insert a single row data, but if I insert more than one row data, it will show the error like :
Violation of PRIMARY KEY constraint 'PK__Expense__EBE72675160F4887'. Cannot insert duplicate key in object 'dbo.Expense'.\r\nThe statement has been terminated.
public System.Guid MaintenanceId { get; set; }
public System.Guid ExpenseSummaryId { get; set; }
public string BillNo { get; set; }
public Nullable<System.DateTime> BillDate { get; set; }
public string VechicleNo { get; set; }
public string ServiceType { get; set; }
public Nullable<double> Amount { get; set; }
public string Reason { get; set; }
public Nullable<System.Guid> UserRightsId { get; set; }
public Nullable<System.Guid> EmployeeId { get; set; }
public string ProviderName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string ProviderCity { get; set; }
public string ProviderState { get; set; }
public string ProviderCountry { get; set; }
public string Pincode { get; set; }
public int Sno { get; set; }
public Nullable<bool> IsActive { get; set; }
public Nullable<bool> IsDeleted { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<System.DateTime> EditedDate { get; set; }
public Nullable<System.DateTime> LastActiveOn { get; set; }
public Nullable<System.Guid> RowID { get; set; }
public Nullable<System.Guid> CreatedSessionID { get; set; }
public Nullable<System.Guid> EditedSessionID { get; set; }
public Nullable<bool> OfflineMode { get; set; }
public Nullable<System.Guid> OfflineID { get; set; }
public List<Expense> Expenses { get; set; }
public virtual Employee Employee { get; set; }
public virtual UserRight UserRight { get; set; }
Here is My Controller
public JsonResult SaveOrder(TruckVM TVM)
{
bool status = false;
if (ModelState.IsValid)
{
using (TestDBEntities db = new TestDBEntities())
{
var guid = Guid.NewGuid();
maintenance ObjMaintenance = new maintenance
{
MaintenanceId=guid,
BillNo=TVM.BillNo,
BillDate=TVM.BillDate,
Amount=TVM.Amount
};
foreach (var i in TVM.Expenses)
{
ObjMaintenance.Expenses.Add(i);
}
db.maintenances.Add(ObjMaintenance);
//db.serviceproviders.Add(ObjServiceProvider);
db.SaveChanges();
status = true;
}
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status } };
}`
here is my view
$(document).ready(function () {
var orderItems = [];
$('#add').click(function () {
var isValidItem = true;
if ($('#Particulars').val().trim() == '') {
isValidItem = false;
$('#Particulars').siblings('span.error').css('visibility', 'visible');
}
else {
$('#Particulars').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#qty').val().trim() != '' && !isNaN($('#qty').val().trim()))) {
isValidItem = false;
$('#qty').siblings('span.error').css('visibility', 'visible');
}
else {
$('#qty').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({
Particulars: $('#Particulars').val().trim(),
qty: parseInt($('#qty').val().trim()),
unitprice: parseFloat($('#unitprice').val().trim()),
TotalAmount: parseInt($('#qty').val().trim()) * parseFloat($('#unitprice').val().trim())
});
//Clear fields
$('#Particulars').val('').focus();
$('#qty').val('')
$('#unitprice').val('')
}
GeneratedItemsTable();
});
$('#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 ($('#BillNo').val().trim() == '') {
$('#BillNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#BillNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#BillDate').val().trim() == '') {
$('#BillDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#BillDate').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
BillNo: $('#BillNo').val().trim(),
BillDate: $('#BillDate').val().trim(),
Amount: $('#Amount').val().trim(),
Expenses: orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/VechicleMaintenance/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 = [];
$('#BillNo').val('');
$('#BillDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
}
});
function GeneratedItemsTable() {
if (orderItems.length > 0) {
var $table = $('<table/>');
$table.append('<thead><tr><th>Particulars</th><th>qty</th><th>unitprice</th><th>TotalAmount</th></tr></thead>');
var $tbody = $('<tbody/>');
$.each(orderItems, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.Particulars));
$row.append($('<td/>').html(val.qty));
$row.append($('<td/>').html(val.unitprice));
$row.append($('<td/>').html(val.TotalAmount));
$tbody.append($row);
});
$table.append($tbody);
$('#orderItems').html($table);
}
}
});
<table width="100%">
<tr>
<td>Particulars</td>
<td>qty</td>
<td>unitprice</td>
<td> </td>
</tr>
<tr>
<td>
<input type="text" id="Particulars" />
<span class="error">Item name required</span>
</td>
<td>
<input type="text" id="qty" />
<span class="error">Valid quantity required</span>
</td>
<td>
<input type="text" id="unitprice" />
<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 id="submit" type="button" value="Save" style="padding:10px 20px" />
</div>