In database 0 is saved for dynamically rows
1. Create.cs html as follows<input type="hidden" id="brandIDInputdetail_0" asp-for="LabelDetails[0].brandID" />
<div class="row" data-rowid="0">
<div class="col-3">
<label asp-for="LabelDetails[0].brandID">Brand Id</label>
</div>
<div class="col-3">
<label asp-for="LabelDetails[0].quantity">Quantity</label>
</div>
<div class="col-3">
<label asp-for="LabelDetails[0].Rate">Rate</label>
</div>
<div class="col-3" style="display:none">
<label asp-for="LabelDetails[0].amount">Amount</label>
</div>
<div class="col-3">
<label asp-for="LabelDetails[0].totalAmount">Total Amount</label>
</div>
</div>
<div class="row">
<div class"col-lg-12">
<div class="mb-3">
<button type="button" id="addRow" class="btn btn-primary">Add Demand Detail</button>
</div>
</div>
</div>
<div id="labelDetailsContainer" data-brands="@Json.Serialize(ViewBag.demandMasterBrands)">
<div class="row" data-rowid="0">
<div class="col-3">
<select id="selectedBrandName" class="form-control" asp-for="LabelDetails[0].brandID" asp-items="ViewBag.demandMasterBrands">
<option value="">--Select brandID--</option>
</select>
<span asp-validation-for="LabelDetails[0].brandID" class="text-danger"></span>
</div>
<div class="col-3">
<input asp-for="LabelDetails[0].quantity" class="form-control quantityInputdetail" />
<span asp-validation-for="LabelDetails[0].quantity" class="text-danger"></span>
</div>
<div class="col-3">
<input asp-for="LabelDetails[0].Rate" class="form-control rateInputdetail" />
<span asp-validation-for="LabelDetails[0].Rate" class="text-danger"></span>
</div>
<div class="col-3" style="display:none">
<input asp-for="LabelDetails[0].amount" class="form-control amountInputdetail" />
<span asp-validation-for="LabelDetails[0].amount" class="text-danger"></span>
</div>
<div class="col-3" style="display:none">
<input class="form-control taxAmountInputdetail" disabled />
</div>
<div class="col-3">
<input asp-for="LabelDetails[0].totalAmount" class="form-control totalAmountInputdetail" />
<span asp-validation-for="LabelDetails[0].totalAmount" class="text-danger"></span>
</div>
</div>
</div>
@section Scripts {
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#selectedBrandName').on('change', function () {
var selectedBrand = $(this).val();
console.log('Selected brand:', selectedBrand);
var row = $(this).closest('.row');
var rowId = row.data("rowid");
$('#brandIDInputdetail_' + rowId).val(selectedBrand);
fetchBrandRateDetail(selectedBrand, row.find('.rateInputdetail'), rowId);
});
let rowCounter = 0;
$("#addRow").click(function () {
const container = $("#labelDetailsContainer");
newRow = container.find(".row").first().clone();
rowCounter++;
const rowId = rowCounter;
newRow.attr("data-rowid", rowId);
newRow.find("input, select").each(function () {
const originalName = $(this).attr("name");
if (originalName) {
const newName = originalName.replace("[0]", `[${rowCounter}]`);
$(this).attr("name", newName);
}
$(this).val("");
});
// Update brandID for the cloned row based on the selected brand name
const selectedBrandName = newRow.find('#selectedBrandName').val();
const brandIDInput = newRow.find(`#brandIDInputdetail_${rowId}`);
const brandID = getBrandIDFromName(selectedBrandName, brands);
brandIDInput.val(brandID);
$(this).val(""); // Clear the input/select values
container.append(newRow);
handleBrandChange(newRow, rowId);
});
function getBrandIDFromName(selectedBrandName, brands) {
for (let i = 0; i < brands.length; i++) {
const brand = brands[i];
if (brand.text === selectedBrandName) {
return brand.value; // Assuming that the brandID is stored in the "value" property
}
}
return ""; // Return an empty string or handle the case where no match is found
}
function handleBrandChange(row, rowId) {
row.find('#selectedBrandName').on('change', function () {
var selectedBrand = $(this).val();
$('#brandIDInputdetail_' + rowId).val(selectedBrand);
fetchBrandRateDetail(selectedBrand, row.find('.rateInputdetail'), rowId);
});
}
function fetchBrandRateDetail(selectedBrand, rateInputElements, rowId) {
console.log('Selected Brand:', selectedBrand);
console.log('Row ID:', rowId);
$.ajax({
url: '/LabelMaster/GetBrandRate',
method: 'GET',
data: { brandName: selectedBrand },
success: function (response) {
var brandRate = response.rate;
rateInputElements.val(brandRate);
$('#brandIDInputdetail_' + rowId).val(response.brandID);
var row = rateInputElements.closest('.row');
calculatetDetailAmount(row);
},
error: function (error) {
console.error('Error fetching brand rate:', error);
}
});
}
document.addEventListener('DOMContentLoaded', function () {
let table = new DataTable('#LabelMasterList', {
scrollX: true,
pagingType: 'full_numbers',
displayLength: 3
});
});
function calculatetDetailAmount(row) {
var quantityInput = row.find('.quantityInputdetail');
var rateInput = row.find('.rateInputdetail');
var amountInput = row.find('.amountInputdetail');
var taxAmountInput = row.find('.taxAmountInputdetail');
var totalAmountInput = row.find('.totalAmountInputdetail');
var quantity = parseFloat(quantityInput.val());
var rate = parseFloat(rateInput.val());
if (!isNaN(quantity) && !isNaN(rate)) {
var amount = quantity * rate;
var taxPercentage = parseFloat($('#TaxPercentage').data('tax-percentage'));
var taxAmount = amount * taxPercentage;
var totalAmount = amount + taxAmount;
amountInput.val(amount.toFixed(2));
taxAmountInput.val(taxAmount.toFixed(2));
totalAmountInput.val(totalAmount.toFixed(2));
}
}
$('#labelDetailsContainer').on('input', '.quantityInputdetail', function () {
var parentRow = $(this).closest('.row');
calculatetDetailAmount(parentRow);
});
});
</script>
}
2.LabelDetails models as follows
public class LabelDetails
{
[Key]
public int demandID { get; set; }
public string brandID { get; set; }
[DisplayName("quantity")]
[Required(ErrorMessage = "Quantity can't be blank")]
public int quantity { get; set; }
public decimal Rate { get; set; }
public decimal amount { get; set; }
public decimal taxPercentage { get; set; }
public decimal taxAmount { get; set; }
public decimal totalAmount { get; set; }
public DateTime CreatedOn { get; set; }
public long Createdby { get; set; }
public DateTime ModifiedOn { get; set; }
public long ModifiedBy { get; set; }
public int IsArchieve { get; set; }
}
3. Labelmaster controller code as follows
[HttpPost]
public IActionResult Create(ManufacturerSupplierModel model)
{
try
{
if (ModelState.IsValid)
{
var labelMasterDemandModel = new LabelMasterDemand
{
licenseeID = model.MasterDemand[0].licenseeID,
licenseeType = model.MasterDemand[0].licenseeType,
quantity = model.MasterDemand[0].quantity,
amount = model.MasterDemand[0].amount
};
labelMasterDemandModel.brandID = model.MasterDemand[0].brandID;
labelMasterDemandModel.taxAmount = labelMasterDemandModel.amount * _appSettings.TaxPercentage;
labelMasterDemandModel.totalAmount = labelMasterDemandModel.amount + labelMasterDemandModel.taxAmount;
int status;
int demandId;
status = _masterDemandService.AddDemandMaster(labelMasterDemandModel, out demandId);
if (status == 1)
{
TempData["success"] = "Indent created successfully !";
TempData["Valid"] = "1";
foreach (var detail in model.LabelDetails)
{
var labelDetails = new LabelDetails
{
demandID = demandId,
brandID = detail.brandID,
quantity = detail.quantity,
Rate = detail.Rate,
amount = detail.quantity * detail.Rate
};
Console.WriteLine($"Brand ID: {labelDetails.brandID}");
labelDetails.taxAmount = labelDetails.amount * _appSettings.TaxPercentage;
labelDetails.totalAmount = labelDetails.amount + labelDetails.taxAmount;
int result;
result = _masterDemandService.AddLabelDetails(labelDetails);
if (result == 1)
{
TempData["success"] = "Indents created successfully !";
TempData["Valid"] = "1";
}
else
{
TempData["success"] = "Error... indents not added!";
TempData["Valid"] = "0";
}
}
}
else
{
TempData["success"] = "Error... master not added!";
TempData["Valid"] = "0";
}
return RedirectToAction("Index");
}
return View(model);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
TempData["success"] = "An error occurred. Please try again later.";
TempData["Valid"] = "0";
return RedirectToAction("Index");
}
}
4. Masterdemandservice code as follows
public int AddLabelDetails(LabelDetails details)
{
int status;
try
{
int demandId;
demandId = details.demandID;
if (demandId > 0)
{
var parameter = new List<MySqlConnector.MySqlParameter>();
parameter.Add(new MySqlConnector.MySqlParameter("@p_demandID", details.demandID));
parameter.Add(new MySqlConnector.MySqlParameter("@p_brandID", details.brandID));
parameter.Add(new MySqlConnector.MySqlParameter("@p_quantity", details.quantity));
parameter.Add(new MySqlConnector.MySqlParameter("@p_Rate", details.Rate));
parameter.Add(new MySqlConnector.MySqlParameter("@p_amount", details.amount));
parameter.Add(new MySqlConnector.MySqlParameter("@p_taxPercentage", details.taxPercentage));
parameter.Add(new MySqlConnector.MySqlParameter("@p_taxAmount", details.taxAmount));
parameter.Add(new MySqlConnector.MySqlParameter("@p_totalAmount", details.totalAmount));
parameter.Add(new MySqlConnector.MySqlParameter("@p_CreatedOn", DateTime.Now.ToString()));
parameter.Add(new MySqlConnector.MySqlParameter("@p_CreatedBy", 1));
parameter.Add(new MySqlConnector.MySqlParameter("@p_ModifierOn", DateTime.Now.ToString()));
parameter.Add(new MySqlConnector.MySqlParameter("@p_ModifiedBy", 1));
parameter.Add(new MySqlConnector.MySqlParameter("@IsArchieve", 1));
var query = $"CALL sp_AddDemandDetails(@p_demandID,@p_brandID,@p_quantity,@p_Rate,@p_amount,@p_taxPercentage,@p_taxAmount,@p_totalAmount,@p_CreatedOn,@p_CreatedBy,@p_ModifierOn,@p_ModifiedBy,@IsArchieve)";
status = _dbContext.Database.ExecuteSqlRaw(query, parameter.ToArray());
}
else
{
status = -1;
}
return status;
}
catch
{
return -1;
}
}
Brandid Quantity Rate Totalamount
Add Demand Detail (Button)
Brand Quantity Rate Totalamount
Beer 120 10 1416.00 --First row
RUM 250 5 1475.00 --Dynamically row
When i click save button in the below cpe_elu_demand_details table brandid 7 is inserted correctly for firstrow.
but for the Dynamically row brandid 0 is saved into cpe_elu_demand_details.
demanddetaild demandid brandid quantity Rate amount taxamount totalamount
2 1 7 120 10 1200 216.00 1416.00 --first row
3 1 0 120 10 1200 216.00 1416.00 --dynamically row
i have tired for 100 times i think so but always for dynamically row brandid 0 is saved
Masterdemandservice debug information as follows
Note: When i debug the below code for first row branid 7 is displayed but for dynamically row i can see brandname RUM
parameter.Add(new MySqlConnector.MySqlParameter("@p_brandID", details.brandID)); -- for first row brandid 7
parameter.Add(new MySqlConnector.MySqlParameter("@p_brandID", details.brandID)); -- for dynamically row i can see brandname RUM
Labelmaster controller debug information as follows
Note: When i debug the below code for first row branid 7 is displayed but for dynamically row i can see brandname RUM
Console.WriteLine($"Brand ID: {labelDetails.brandID}"); -->-- for first row brandid 7
Console.WriteLine($"Brand ID: {labelDetails.brandID}"); -->-- for dynamically row i can see brandname RUM
what is misake in the code.