Read Datatable Rows when postback Razor Pages - javascript

As shown in the Image, I fill the data table with the add row button from the fields in the form, once I add all the needed rows (Order Creation) Create button will be clicked, I want to send the data of the data table that was created on the client-side to the server-side so I can save them in the database, how to do this?
My Create Form
Server-side code below
public class CreateModel : PageModel
{
private readonly ArabianCement.Models.ArabianCementContext _context;
private readonly IConfiguration _configuration;
public CreateModel(ArabianCement.Models.ArabianCementContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
[BindProperty]
public Guid VendorGUIDBind { get; set; }
[BindProperty]
public List<tbl_AC_Trans_Detail> gridBind { get; set; } = new List<tbl_AC_Trans_Detail>();
public IActionResult OnGet()
{
ViewData["AC_Trans_GUID"] = new SelectList(_context.tbl_AC_Trans, "AC_Trans_GUID", "AC_Trans_GUID");
ViewData["Cement_GUID"] = new SelectList(_context.LK_Cements, "Cement_GUID", "Cement_Name");
ViewData["Vendor_GUID"] = new SelectList(_context.LK_Sources, "Source_GUID", "Source_Name");
return Page();
}
[BindProperty]
public tbl_AC_Trans_Detail tbl_AC_Trans_Detail { get; set; }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
tbl_AC_Tran objMainTrans = new tbl_AC_Tran();
Guid sellGUID = Guid.Parse(_configuration["AppKeys:SellGUID"]);
objMainTrans.AC_Trans_GUID = Guid.NewGuid();
objMainTrans.Creation_Date = DateTime.Now;
objMainTrans.Vendor_GUID = VendorGUIDBind;
objMainTrans.Trans_Type = sellGUID;
//_context.tbl_AC_Trans.Add(objMainTrans);
//await _context.SaveChangesAsync();
//_context.tbl_AC_Trans_Details.Add(tbl_AC_Trans_Detail);
// await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
return RedirectToPage();
}
public IEnumerable<LK_Cement_Type> GetModels(Guid cementGUID)
{
IEnumerable<LK_Cement_Type> model = _context.LK_Cement_Types.Where(x => x.Cement_GUID == cementGUID).ToList();
return model;
}
public JsonResult OnGetCementTypes(string id)
{
Guid guid = Guid.Parse(id);
return new JsonResult(GetModels(guid));
}
}
cshtml code below
#using Newtonsoft.Json;
#using System.Web;
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>tbl_AC_Trans_Detail</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="form-control" />
<span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
</div>*#
<div class="form-group">
<label class="control-label">Vendor</label>
<select asp-for="VendorGUIDBind" class ="form-control" asp-items="ViewBag.Vendor_GUID" id="ddlVendor">
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.Cement_GUID" class ="form-control" asp-items="ViewBag.Cement_GUID" id="ddlCement">
<option value="">Select Cement</option>
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class ="form-control" asp-items="ViewBag.Cement_Type_GUID" id="ddlCementType">
<option value="">Select Cement Type</option>
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="control-label">Cement Quantity</label>
<input asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="form-control" id="txtCementQuantity"/>
<span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Price" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.Cement_Price" class="form-control" id="txtCementPrice" />
<span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Total_Amount" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.Total_Amount" class="form-control" id="txtTotalAmount" />
<span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" class="text-danger"></span>
</div>
<div class="form-group">
#*<input type="submit" value="Create" class="btn btn-primary" asp-action="OnPostAsync" />*#
<input type="submit" value="Create" class="btn btn-primary" onclick="testFun()" />
<input type="button" value="addRow" class="btn btn-primary" onclick="AddProduct()" />
</div>
</form>
</div>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Vendor GUID</th>
<th>Vendor Name</th>
<th>Cement Guid</th>
<th>Cement Name</th>
<th>Cement Type Guid</th>
<th>Cement Type Name</th>
<th>Quantity </th>
<th>Cement Price</th>
<th>Total</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$("#ddlCement").on("change", function() {
var cement = $(this).val();
$("#ddlCementType").empty();
$("#ddlCementType").append("<option value=''>Select Type</option>");
$.getJSON("?handler=CementTypes",{ id: cement}, (data) => {
$.each(data, function (i, item) {
$("#ddlCementType").append('<option value='+item.cement_Type_GUID+'>'+item.cement_Type_Name+'</option>');
});
});
});
});
$("#txtCementQuantity,#txtCementPrice").focusout(function () {
//alert('ddlCurrency');
var cementQuantity = document.getElementById("txtCementQuantity").value;
var cementPrice = document.getElementById("txtCementPrice").value;
var totalAmount=0;
document.getElementById("txtTotalAmount").value = cementQuantity * cementPrice;
});
function AddProduct() {
var t = $('#example').DataTable();
var counter = 1;
t.row.add( [
$("#ddlVendor Option:Selected").val(),
$("#ddlVendor Option:Selected").text(),
$("#ddlCement Option:Selected").val(),
$("#ddlCement Option:Selected").text(),
$("#ddlCementType Option:Selected").val(),
$("#ddlCementType Option:Selected").text(),
document.getElementById("txtCementQuantity").value,
document.getElementById("txtCementPrice").value,
document.getElementById("txtTotalAmount").value
] ).draw();
counter++;
}
function testFun()
{
//var json = JsonConvert.SerializeObject(Html(#e), Formatting.Indented);
alert('Test');
}
$(document).ready(function () {
$("#example2").DataTable({
"paging": true,
responsive: true,
"searching": true,
"ordering": true,
dom: 'Bfrtip',
buttons: [
'excel'
],
"order": [[1, "asc"]]
});
});
</script>
}

You can try to put rowdata into hidden div of the form when click AddRow button.Also,you need to remove onclick="testFun()".Here is a demo to pass rows data to List<TestModel> AddedRows:
cshtml:
#using Newtonsoft.Json;
#using System.Web;
#{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>tbl_AC_Trans_Detail</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="form-control" />
<span asp-validation-for="tbl_AC_Trans_Detail.AC_Trans_Detail_GUID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.AC_Trans_GUID" class ="form-control" asp-items="ViewBag.AC_Trans_GUID"></select>
</div>*#
<div class="form-group">
<label class="control-label">Vendor</label>
<select asp-for="VendorGUIDBind" class ="form-control" asp-items="ViewBag.Vendor_GUID" id="ddlVendor">
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.Cement_GUID" class ="form-control" asp-items="ViewBag.Cement_GUID" id="ddlCement">
<option value="">Select Cement</option>
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class="control-label"></label>
<select asp-for="tbl_AC_Trans_Detail.Cement_Type_GUID" class ="form-control" asp-items="ViewBag.Cement_Type_GUID" id="ddlCementType">
<option value="">Select Cement Type</option>
</select>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="control-label">Cement Quantity</label>
<input asp-for="tbl_AC_Trans_Detail.Cement_Quantity" class="form-control" id="txtCementQuantity"/>
<span asp-validation-for="tbl_AC_Trans_Detail.Cement_Quantity" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Cement_Price" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.Cement_Price" class="form-control" id="txtCementPrice" />
<span asp-validation-for="tbl_AC_Trans_Detail.Cement_Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="tbl_AC_Trans_Detail.Total_Amount" class="control-label"></label>
<input asp-for="tbl_AC_Trans_Detail.Total_Amount" class="form-control" id="txtTotalAmount" />
<span asp-validation-for="tbl_AC_Trans_Detail.Total_Amount" class="text-danger"></span>
</div>
<div id="hiddenData" style="display: none;">
</div>
<div class="form-group">
#*<input type="submit" value="Create" class="btn btn-primary" asp-action="OnPostAsync" />*#
<input type="submit" value="Create" class="btn btn-primary"/>
<input type="button" value="addRow" class="btn btn-primary" onclick="AddProduct()" />
</div>
</form>
</div>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Vendor GUID</th>
<th>Vendor Name</th>
<th>Cement Guid</th>
<th>Cement Name</th>
<th>Cement Type Guid</th>
<th>Cement Type Name</th>
<th>Quantity </th>
<th>Cement Price</th>
<th>Total</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
var index = 0;
$(function () {
$("#ddlCement").on("change", function() {
var cement = $(this).val();
$("#ddlCementType").empty();
$("#ddlCementType").append("<option value=''>Select Type</option>");
$.getJSON("?handler=CementTypes",{ id: cement}, (data) => {
$.each(data, function (i, item) {
$("#ddlCementType").append('<option value='+item.cement_Type_GUID+'>'+item.cement_Type_Name+'</option>');
});
});
});
});
$("#txtCementQuantity,#txtCementPrice").focusout(function () {
//alert('ddlCurrency');
var cementQuantity = document.getElementById("txtCementQuantity").value;
var cementPrice = document.getElementById("txtCementPrice").value;
var totalAmount=0;
document.getElementById("txtTotalAmount").value = cementQuantity * cementPrice;
});
function AddProduct() {
var t = $('#example').DataTable();
var counter = 1;
t.row.add( [
$("#ddlVendor Option:Selected").val(),
$("#ddlVendor Option:Selected").text(),
$("#ddlCement Option:Selected").val(),
$("#ddlCement Option:Selected").text(),
$("#ddlCementType Option:Selected").val(),
$("#ddlCementType Option:Selected").text(),
document.getElementById("txtCementQuantity").value,
document.getElementById("txtCementPrice").value,
document.getElementById("txtTotalAmount").value
] ).draw();
const div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<input type="text" name="AddedRows[' + index + '].Vendor_GUID" value="' + $("#ddlVendor Option:Selected").val() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Vendor_Name" value="' + $("#ddlVendor Option:Selected").text() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_GUID" value="' + $("#ddlCement Option:Selected").val() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_Name" value="' + $("#ddlCement Option:Selected").text() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_Type_GUID" value="' + $("#ddlCementType Option:Selected").val() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_Type_Name" value="' + $("#ddlCementType Option:Selected").text() + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_Quantity" value="' + document.getElementById("txtCementQuantity").value + '" />' +
'<input type="text" name="AddedRows[' + index + '].Cement_Price" value="' + document.getElementById("txtCementPrice").value + '" />' +
'<input type="text" name="AddedRows[' + index + '].Total_Amount" value="' + document.getElementById("txtTotalAmount").value + '" />' ;
document.getElementById('hiddenData').appendChild(div);
index++;
counter++;
}
function testFun()
{
//var json = JsonConvert.SerializeObject(Html(#e), Formatting.Indented);
alert('Test');
}
$(document).ready(function () {
$("#example2").DataTable({
"paging": true,
responsive: true,
"searching": true,
"ordering": true,
dom: 'Bfrtip',
buttons: [
'excel'
],
"order": [[1, "asc"]]
});
});
</script>
}
cshtml.cs:
public class CreateModel : PageModel
{
private readonly ArabianCement.Models.ArabianCementContext _context;
private readonly IConfiguration _configuration;
public CreateModel(ArabianCement.Models.ArabianCementContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
[BindProperty]
public Guid VendorGUIDBind { get; set; }
[BindProperty]
public List<tbl_AC_Trans_Detail> gridBind { get; set; } = new List<tbl_AC_Trans_Detail>();
[BindProperty]
public List<TestModel> AddedRows { get; set; }
public IActionResult OnGet()
{
ViewData["AC_Trans_GUID"] = new SelectList(_context.tbl_AC_Trans, "AC_Trans_GUID", "AC_Trans_GUID");
ViewData["Cement_GUID"] = new SelectList(_context.LK_Cements, "Cement_GUID", "Cement_Name");
ViewData["Vendor_GUID"] = new SelectList(_context.LK_Sources, "Source_GUID", "Source_Name");
return Page();
}
[BindProperty]
public tbl_AC_Trans_Detail tbl_AC_Trans_Detail { get; set; }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
tbl_AC_Tran objMainTrans = new tbl_AC_Tran();
Guid sellGUID = Guid.Parse(_configuration["AppKeys:SellGUID"]);
objMainTrans.AC_Trans_GUID = Guid.NewGuid();
objMainTrans.Creation_Date = DateTime.Now;
objMainTrans.Vendor_GUID = VendorGUIDBind;
objMainTrans.Trans_Type = sellGUID;
//_context.tbl_AC_Trans.Add(objMainTrans);
//await _context.SaveChangesAsync();
//_context.tbl_AC_Trans_Details.Add(tbl_AC_Trans_Detail);
// await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
return RedirectToPage();
}
public IEnumerable<LK_Cement_Type> GetModels(Guid cementGUID)
{
IEnumerable<LK_Cement_Type> model = _context.LK_Cement_Types.Where(x => x.Cement_GUID == cementGUID).ToList();
return model;
}
public JsonResult OnGetCementTypes(string id)
{
Guid guid = Guid.Parse(id);
return new JsonResult(GetModels(guid));
}
}
public class TestModel {
public Guid Vendor_GUID { get; set; }
public string Vendor_Name { get; set; }
public Guid Cement_GUID { get; set; }
public string Cement_Name { get; set; }
public Guid Cement_Type_GUID { get; set; }
public string Cement_Type_Name { get; set; }
public int Cement_Quantity { get; set; }
public int Cement_Price { get; set; }
public int Total_Amount { get; set; }
}

Related

Controller not receiving list of Model in Asp.net Core

I am trying to send the data from my view to controller, I created a PO, then on the next page I viewed the products to show and to select by the user. but when user select and post the data, controller didn't get that.
Here is a controller data
public IActionResult CreatePO()
{
var LastPO = _context.PurchaseOrders.OrderByDescending(p => p.PONumber).FirstOrDefault();
int TempPO = Convert.ToInt32(LastPO.PONumber.Replace("PO", "")) + 1;
var NewPO = "PO" + TempPO.ToString().PadLeft(6, '0');
ViewBag.NewPO = NewPO;
var UserData = _context.Users.Where(a => a.UserName == User.Identity.Name).SingleOrDefault();
List<Vendor> vendors = _context.Vendors.Where(e => e.CreatedBy == UserData.UserId).ToList();
ViewBag.Vendors = vendors;
return View();
}
[HttpPost]
public IActionResult CreatePO(PurchaseOrder model)
{
if (ModelState.IsValid)
{
var UserData = _context.Users.Where(a => a.UserName == User.Identity.Name).SingleOrDefault();
model.CreatedBy = UserData.UserId;
model.UpdatedBy = UserData.UserId;
return RedirectToAction("AddProduct", new {VendorId = model.VendorId , PONumber = model.PONumber});
}
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult AddProduct(int? VendorId, string? PONumber)
{
if (VendorId == null || PONumber == null)
{
VendorId = 2;
PONumber = "PO00002";
}
List<Product> products = _context.Products.Where(e => e.VendorId == VendorId && e.Stock > 0).ToList();
var VenderData = _context.Vendors.Where(a => a.Id == VendorId).SingleOrDefault();
ViewBag.VendorId = VenderData.VendorName;
ViewBag.PONumber = PONumber;
ViewBag.Products = products;
return View();
}
[HttpPost]
public IActionResult AddProduct(IEnumerable<OrderProducts> ListOfOrderProducts)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
Here is the View of Products to Add
#{
ViewData["Title"] = "Add Products";
}
<link href="~/css/sheet1.css" rel="stylesheet" />
<script src="~/js/pojavascript.js"></script>
<form method="post" onsubmit="return validateForm2()">
<div class="border p-3 mt-4">
<div class="row pb-3">
<h2>
Select Products
</h2>
<hr />
</div>
#if (TempData["SuccessMsg"] != null)
{
<div class="alert alert-dismissible alert-success">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<strong>#TempData["SuccessMsg"]</strong>
</div>
}
else if (TempData["ErrorMsg"] != null)
{
<div class="alert alert-dismissible alert-danger">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<strong>#TempData["ErrorMsg"]</strong>
</div>
}
<div class="row m-3 mb-3">
<label></label>
<input id="PONumber" readonly value="#ViewBag.PONumber" type="text" class="form-control" />
</div>
<div class="row m-3 mb-3">
<label></label>
<input id="VendorId" readonly value="#ViewBag.VendorId" type="text" class="form-control" />
</div>
<div class="row m-2 mb-3">
<div class="col-md-6 mb-4">
<label>Select Product</label>
<select id="Products" class="form-select">
<option value="0">Select Product</option>
#{
var i = 1;
}
#foreach(var ProData in ViewBag.Products)
{
<option value="tr_#i">(#ProData.SKU) #ProData.ProductName</option>
i = i + 1;
}
</select>
</div>
<div class="col-md-6 mb-4">
<button onclick="AddRow()" type="button" style="margin-top:25px" class="btn btn-primary">
Add
</button>
</div>
</div>
<div class="row m-2 mb-3">
<table class="table table-bordered table-striped" id="POTable">
<thead>
<tr>
<th>
Select
</th>
<th>
Product ID
</th>
<th>
SKU
</th>
<th>
Product Name
</th>
<th style="width:200px">
Add Item
</th>
<th>
Price
</th>
<th>
Total Amount
</th>
</tr>
</thead>
<tbody>
#{i = 1;}
#foreach (var ProData in ViewBag.Products)
{
<tr id="tr_#i">
<input id="PONumber_#i" type="hidden" value="#ViewBag.PONumber">
<input id="VendorId_#i" type="hidden" value="#ViewBag.VendorId">
<input id="CreatedDate_#i" type="hidden" value="#DateTime.Now">
<td>
<input id="Chk_products_#i" class="form-check-input" onclick="CheckRow(this, #i)" type="checkbox">
</td>
<td>
<input id="Pr_ID_#i" type="text" class="form-control" value="#ProData.ProductId">
</td>
<td>
<input id="Pr_Name_#i" type="text" class="form-control" value="#ProData.ProductName">
</td>
<td>
<input id="SKU_#i" type="text" class="form-control" value="#ProData.SKU">
</td>
<td>
<div class="qty">
<button onclick="AddSub(#i ,0)" type="button" class="btn btn-primary" style="margin-bottom:5px">-</button>
<input id="count_#i" type="number" class="form-control" style="width:80px;display:inline-block;" name="qty_#i" value="1">
<button onclick="AddSub(#i ,1)" type="button" class="btn btn-primary" style="margin-bottom:5px">+</button>
</div>
</td>
<td>
<input id="UnitPrice_#i" type="number" class="form-control" value="#ProData.UnitOfPrice">
</td>
<td>
<input id="TAmount_#i" type="number" class="form-control" value="#ProData.UnitOfPrice">
</td>
</tr>
i = i + 1;
}
</tbody>
</table>
<table class="table table-bordered table-striped" style="width:60%;margin-top:30px">
<tr>
<th>Total No of Items</th>
<td>
<input readonly type="text" id="TotItems" class="form-control" value="0" />
</td>
</tr>
<tr>
<th>Total No of Products</th>
<td>
<input readonly type="text" id="TotProducts" class="form-control" value="0" />
</td>
</tr>
<tr>
<th>Total Bill</th>
<td>
<input readonly type="text" id="TotAmount" class="form-control" value="0.00" />
</td>
</tr>
<tr>
<th>Remaining Amount</th>
<td>
<input readonly type="text" id="RemAmount" class="form-control" value="0.00" />
</td>
</tr>
</table>
<div class="row m-2 mb-3">
<div class="mb-2">
<h4 style="display:inline;">Enter amount to pay</h4>
<div class="input-group mb-3" style="width:50%">
<span class="input-group-text">$</span>
<input id="TotPaid" type="text" value="0.00" class="form-control">
<span class="input-group-text">.00</span>
</div>
</div>
</div>
</div>
<button onclick="AjaxFormData()" class="btn btn-primary ms-lg-3" type="button" style="width:100px; margin-top:20px">
Create
</button>
</div>
</form>
Here is the JavaScript Ajax Call Function
function AjaxFormData() {
var ListOfOrderProducts = new Array();
var table = document.getElementById('POTable');
if (table.rows.length != 0) {
for (let i = 1; i < table.rows.length; i++) {
CheckBoxVal = document.getElementById("Chk_products_" + i);
if (CheckBoxVal.checked) {
var memberDetails = {};
memberDetails.VendorId = document.getElementById("VendorId").value;
memberDetails.PONumber = document.getElementById("PONumber").value;
memberDetails.POCreatedDate = "2023-02-13";
memberDetails.ProductId = document.getElementById("Pr_ID_" + i).value;
memberDetails.ProductName = document.getElementById("Pr_Name_" + i).value;
memberDetails.ProductQuantity = document.getElementById("count_" + i).value;
memberDetails.ProductUnitPrice = document.getElementById("UnitPrice_" + i).value;
memberDetails.ProductTotalPrice = document.getElementById("TAmount_" + i).value;
alert(memberDetails.VendorId + " " + memberDetails.PONumber + " " + memberDetails.ProductId);
ListOfOrderProducts.push(memberDetails);
}
}
}
$.ajax({
async: true,
type: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf=8",
url: "AddProduct",
data: JSON.stringify(ListOfOrderProducts),
success: function (data) {
alert("Hello");
},
error: function () {
alert("Error");
}
});
}
I tried to create it by using 3 models
public class OrderProducts
{
[Key]
public int Id { get; set; }
[Required]
public string PONumber { get; set; }
public DateTime POCreatedDate { get; set; }
[Required]
public int ProductId { get; set; }
public string? .....
public class PurchaseOrder
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "PO Number")]
public string PONumber { get; set; }
[Required]
public int VendorId{ get; set; }
[Display(Name = "Total Products")]
[ValidateNever]
public int TotalProducts { get; set; }
[Display(Name = "Total Items")]
[ValidateNever]
public int TotalItems { get; set; }
[Display(Name = "Total Amount")]
[ValidateNever]
public double TotalAmount { get; set; }
[Display(Name = "Paid Amount")].....
public class POWithOrders
{
public string PONumber { get; set; }
public string VendorId { get; set; }
public DateTime CreatedDate { get; set; }
public List<OrderProducts> ListOfOrderProducts { get; set; }
}
I need help as my Controller (AddProduct) HTTPPOSt didn't get the Data
I provided all details what I have done and what is happening, My controller is not getting the model data, which I am trying to post from view to controller. I don't know what is going on there.
As you are sending Form Data via AJAX you will also need to add the [FromBody] decoration to the PurchaseOrder parameter.
Example
public IActionResult CreatePO([FromBody]PurchaseOrder model)
Resource
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1#sending-form-data-via-ajax

Binding multiple objects to a List<t>

I am trying to bind my model.List NewReportDetails normally this is not an issue. In this case I have users adding additional models to the list via Ajax. When they hit Submit I can see the default model but the List is empty.
Here is my Models
Index Model:
public List<ShiftReport> ShiftReportList { get; set; }
public ShiftReport NewReport { get; set; }
public List<ShiftReportDetail> NewReportDetails { get; set; }
public List<UserListsForSignatures> ListOfNames { get; set; }
public List<ProductCodes> ProductsList { get; set; }
public List<EquipList> Equipment { get; set; }
ShiftDetailDetail Model:
public int ID { get; set; }
public int ReportID { get; set; }
public int? Area { get; set; }
public string AreaDecoded { get; set; }
public int? Product { get; set; }
public string ProductString { get; set; }
public int Equipment { get; set; }
public string EquipmentString { get; set; }
public string Comment { get; set; }
public string TypeOfTrouble { get; set; }
public string CounterMeasure { get; set; }
public string Time { get; set; }
public string Tag { get; set; }
public string[] TagArray { get; set; }
public int GroupCode { get; set; }
public int TagDupFixer { get; set; }
Here is my controller
index:
public IActionResult Index()
{
ProductionSuperModel model = new()
{
ListOfNames = QualityHelper.GetAllTheNamesWithRoles(1),
ProductsList = _repo.RetrieveProductList(),
Equipment = _repo.RetrieveEquipmentList()
};
// tagduper = 1 means dont run the firsForloop this causes null pointer exeption if left 0
return View(model);
}
NewReportDetails
public PartialViewResult NewReportDetail(int id)
{
ShiftReportDetail model = new()
{
ID = id,
TagDupFixer = 1,
EquipmentList = _repo.RetrieveEquipmentList(),
ProductsList = _repo.RetrieveProductList()
};
return PartialView("_ReportDetail", model);
}
AddReport
[HttpPost]
public IActionResult AddReport(ProductionSuperModel model)
{
return Json(1);
}
Index View
<div id="CreateReportDetail">
</div>
</div>
<div class="modal-footer">
<button type="button" id="SubmitAReport" class="btn btn-primary YearReview">Submit</button>
<button type="button" id="closemodal" class="btn btn-secondary closemodal2" data-dismiss="modal">Close</button>
</div>
Partial View
<div class="NewDetailDiv">
<input asp-for="#Model.ID" hidden />
<input asp-for="#Model.ReportID" hidden />
<input asp-for="#Model.GroupCode" hidden />
<div class="card mb-5" style="background-color: burlywood">
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="form-floating mb-2 mt-2">
<select class="custom-select form-control ModelDisabled Taggable" multiple data-allow-clear="true" asp-for="#Model.TagArray">
<option selected disabled hidden value="">Equipment</option>
#foreach (var names in Model.EquipmentList)
{
<option value="#names.TagName">#names.TagName</option>
}
</select>
<label>Equipment</label>
</div>
</div>
<div class="col-4">
<div class="form-floating mb-2 mt-2">
<select class="custom-select form-control ModelDisabled" asp-for="#Model.AreaDecoded">
<option selected>Please Select</option>
<option value="All">All</option>
<option value="Control Room">Control Room</option>
<option value="Dock">Dock</option>
<option value="Filling Building">Filling Building</option>
<option value="FillingRoom">FillingRoom</option>
<option value="HCA-1&2">HCA-1&2</option>
<option value="HCA1/2/NEU/U">HCA1/2/NEU/U</option>
<option value="HCA1/2/NEU/Utility?T-F">HCA1/2/NEU/Utility?T-F</option>
<option value="HCA-1">HCA-1</option>
<option value="HCA-2">HCA-2</option>
<option value="L598">L598</option>
<option value="L521">L521</option>
<option value="NEU/Utility/T-F">NEU/Utility/T-F</option>
<option value="W211">W211</option>
<option value="W112A">W112A</option>
<option value="Warehouse">Warehouse</option>
</select>
<label>Area</label>
</div>
</div>
<div class="col-4">
<div class="form-floating mb-2 mt-2">
<input asp-for="#Model.Time" class="form-control ModelDisabled" type="text" placeholder="Time" />
<label>Time</label>
</div>
</div>
<div class="col-4">
<div class="form-floating mb-2 mt-2 ">
<input asp-for="#Model.ProductString" class="form-control dataLists ModelDisabled" list="Products" placeholder="Product" />
<datalist id="PeopleDropdown">
<datalist id="Products">
<option value="">Please Select</option>
#foreach (var things in Model.ProductsList)
{
<option value="#things.ProductType">#things.ProductType</option>
}
</datalist>
</datalist>
<label>Product</label>
</div>
</div>
<div class="col-6">
<div class="form-floating mb-2 mt-2">
<textarea asp-for="#Model.TypeOfTrouble" class="form-control ModelDisabled" type="text" placeholder="Type of Trouble"
rows="3" style="height:100%;"></textarea>
<label>Type of Trouble</label>
</div>
</div>
<div class="col-6">
<div class="form-floating mb-2 mt-2">
<textarea asp-for="#Model.CounterMeasure" class="form-control ModelDisabled" type="text" placeholder="Counter Measure"
rows="3" style="height:100%;"></textarea>
<label>Counter Measure</label>
</div>
</div>
<div class="col-12">
<div class="form-floating mb-2 mt-2">
<textarea asp-for="#Model.Comment" class="form-control ModelDisabled" type="text" placeholder="Comment"
rows="3" style="height:100%;"></textarea>
<label>Comment</label>
</div>
</div>
</div>
</div>
</div>
Here is my Javascript
$(document).ready(function () {
$('#CreateReportDetail').load('/Production/NewReportDetail/0');
});
$(".AddMoreReportDetails").click(function () {
// find the right div.
var counter = $('#ReportCounter');
var counterNo = +counter.val() + 1;
counter.val(counterNo);
$('#CreateReportDetail').append($('<div>').load('/Production/NewReportDetail/' + counterNo, function () {
Tags.init(".Taggable");
}));
});
$(document).on("click", "#SubmitReportEdits", function () {
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize(),
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade show' role='alert'> " + "Report has been edited. Thank you." +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" + "<span aria-hidden='true'>×</span>" + "</button>" + "</div>"
);
}
});});
I do see the information on the Request.Form. However the model.List is null. Any help will be greatly appreciated.
Edit --
Full Index.CShtml
#model PortalMVC.Models.Production.ProductionSuperModel;
<div id="NotificationDiv">
</div>
<div class="row justify-content-center">
<div class="col-10 mb-3">
<div class="card">
<div class="card-body">
<div class="row justify-content-between">
<div class="col-6 align-self-center">
<div class="dropdown float-left NAIIbg
RoundCorners">
<span data-toggle="dropdown" aria-
haspopup="true" aria-expanded="false">
<button class="btn btn-secondary
dropdown-toggle NAIIbg border-0
BoxShadow" type="button" id="dropdownMenu2" data-
toggle="tooltip" title="Create Report" aria-
haspopup="true" aria-expanded="false">
<i class="fa fa-id-card" aria-
hidden="true"></i>
</button>
</span>
<div class="dropdown-menu" aria-
labelledby="dropdownMenu2">
<button class="dropdown-item
ReportType" type="button" value="MH">MH
Report</button>
<button class="dropdown-item
ReportType" type="button" value="Maint">Maint
Report</button>
<button class="dropdown-item
ReportType" type="button" value="HCA">HCA Report</button>
<button class="dropdown-item
ReportType" type="button" value="PMCrew">PMCrew
Report</button>
<button class="dropdown-item
ReportType" type="button" value="PAA">PA Report</button>
</div>
</div>
</div>
<div class="col-4">
<div class="form-floating mb-3 mt-3">
<input id="SearchInput" class="form-
control" type="text" placeholder="Search" aria-
controls="EditTbl" />
<label>Search</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="w-100"></div>
<div class="col-10" id="MainReportTbl">
<!--Create a partial here-->
<div style="display:flex;justify-content:center;align-
items:center;background-color:white">
<div class="loader" id="loading2"></div>
</div>
</div>
</div>
full JS here --
import Tags from "https://cdn.jsdelivr.net/gh/lekoala/bootstrap5-
tags#master/tags.js";
$(document).ready(function () {
$("#SearchInput").on("keyup", function () {
$('#EditTbl').DataTable().search(
$('#SearchInput').val()
).draw();
});
$('#CreateReportDetail').load('/Production/NewReportDetail/0');
});
// does the thing for modal for each of the rows.
// logic handler for closing of modal.
$(".closemodal").click(function () {
$('#ReviewReport').modal('toggle');
});
$(".closemodal2").click(function () {
$('#CreateReport').modal('toggle');
});
$(document).on("click", "#EditBtn", function () {
$('.ModelDisabled').each(function () {
$(this).removeAttr("disabled");
});
});
// this calls the modal to open it for viewing.
$(document).on("click", ".tableRowSelector", function () {
var rowInfo = $(this).attr('name');
$("#mod1").empty();
// show the loading.
$("#loading1").removeClass("d-none");
$('#ReviewReport').modal('toggle');
// rowinfo is working get this to the controller for an ajax.
$("#mod1").load("/Production/GetReport/" + rowInfo, function () {
Tags.init(".Taggable");
// hide the loading.
$('.ModelDisabled').each(function () {
$(this).attr('disabled', 'disabled');
});
$("#loading1").addClass("d-none");
});
}).find('tr').click(function (e) {
e.stopPropagation();
});
// this is the one that updates the modal if its being updated
$(document).on("click", "#SubmitReportEdits", function () {
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize(),
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade
show' role='alert'> " + "Report has been edited. Thank you." +
"<button type='button' class='close' data-
dismiss='alert' aria-label='Close'>" + "<span aria-
hidden='true'>×</span>" + "</button>" + "</div>"
);
}
});
});
// this is the function for adding new report
$(document).on("click", "#SubmitAReport", function () {
$.ajax({
type: "POST",
url: $("#AddReportForm").attr("action"),
data: $("#AddReportForm").serialize(),
success: function () {
// close the modal
// reload the table
$('#CreateReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible
fade show' role='alert'> " + "Report has been submitted.
Thank you." +
"<button type='button' class='close' data-
dismiss='alert' aria-label='Close'>" + "<span aria-
hidden='true'>×</span>" + "</button>" + "</div>"
);
}
});
});
$(document).ready(function () {
$("#loading2").removeClass("d-none");
$("#MainReportTbl").load('/Production/MainReportTable',
function () {
var testing = $('#EditTbl').DataTable({
paging: true,
"bInfo": false,
"searching": true,
columnDefs: [
// Center align the header content of column 1
{ className: "dt-head-center", targets: [0, 1, 2, 3]
},
{ type: 'date', 'targets': [0] }
],
order: [[0, , 'desc']]
});
$('#EditTbl_length').addClass('disabled');
$('#EditTbl_filter').addClass('disabled');
$("#loading2").addClass("d-none");
});
});
// create the modal report stuff goes here.
$(".ReportType").click(function () {
var ReportType = $(this).val();
var ModalTitle = ReportType + " Report";
$('#ModalTitle').text(ModalTitle);
// wipe the last report stuff.
$('.NewDetailDiv').remove();
// clean the counter
$('#ReportCounter').val(-1);
// hide show the right ones and show the stuff
if (ReportType == 'HCA' || ReportType == 'MH') {
$('#PMCrewPAMaint').addClass("d-none");
$('#HCAMHReport').removeClass("d-none");
}
else {
$('#PMCrewPAMaint').removeClass("d-none");
$('#HCAMHReport').addClass("d-none");
}
Tags.init(".Taggable");
$('#CreateReport').modal('toggle');
});
// this adds new rows
$(".AddMoreReportDetails").click(function () {
// find the right div.
var counter = $('#ReportCounter');
var counterNo = +counter.val() + 1;
counter.val(counterNo);
$('#CreateReportDetail').
append($('<div>').
load('/Production/NewReportDetail/' + counterNo, function () {
Tags.init(".Taggable");
}));
});
// this deletes row if they added tomany
$(document).on("click", ".DeleteThisDiv", function () {
// find the parent div
var testing =
$(this).parent().closest('div')
.parent().closest('div').parent().closest('div');
$(testing).remove();
});
Sorry about the spacing it was a pain to get it all to look like code. I will try to find a good website so I can post the code there for better reference. Thank you.

How to filter the options of a drop down list using another drop down list asp.net core 3.0

I would like to select a product category in one drop-down list and display subcategories for it.
My models:
ProductCategory
public class ProductCategory
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage ="Pole 'Nazwa kategorii' jest wymagane")]
[Display(Name ="Nazwa kategorii")]
public string Name { get; set; }
[Display(Name = "Dodaj zdjęcie")]
public string ImagePath { get; set; }
public virtual ICollection<ProductSubCategory> ProductSubCategory { get; set; }
}
ProductSubCategory
public class ProductSubCategory
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Pole 'Nazwa podkategorii' jest wymagane")]
[Display(Name = "Nazwa kategorii")]
public string Name { get; set; }
[Display(Name = "Wybierz zdjęcie")]
public string ImagePath { get; set; }
public int ProductCategoryId { get; set; }
[ForeignKey("ProductCategoryId")]
[Display(Name = "Kategoria")]
public ProductCategory ProductCategory { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Create Product Page
public IActionResult OnGet()
{
ViewData["ProductCategoryId"] = new SelectList(_context.ProductCategory, "Id", "Name");
ViewData["ProductSubCategoryId"] = new SelectList(_context.ProductSubCategory, "Id", "Name");
return Page();
}
public JsonResult OnGetSubCategories(int category)
{
var subcategories = _context.ProductSubCategory.Where(c => c.ProductCategoryId == category).ToList();
return new JsonResult(new SelectList(subcategories, "Id", "Name"));
}
CreateProduct html
<form method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Product.Name" class="control-label"></label>
<input asp-for="Product.Name" class="form-control" />
<span asp-validation-for="Product.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.Description" class="control-label"></label>
<input asp-for="Product.Description" class="form-control" />
<span asp-validation-for="Product.Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.ImagePath" class="control-label"></label>
<input type="file" asp-for="Product.ImagePath" class="form-control" name="image" onchange="readURL(this);"/>
<span asp-validation-for="Product.ImagePath" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.DateOfNotification" class="control-label"></label>
<input asp-for="Product.DateOfNotification" class="form-control" />
<span asp-validation-for="Product.DateOfNotification" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.ProductCategoryId" class="control-label"></label>
<select id="category" asp-for="Product.ProductCategoryId" class ="form-control" asp-items="ViewBag.ProductCategoryId"></select>
</div>
<div class="form-group">
<label asp-for="Product.ProductSubCategoryId" class="control-label"></label>
<select id="subCategory" asp-for="Product.ProductSubCategoryId" class ="form-control" asp-items="ViewBag.ProductSubCategoryId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
script
<script>
$("#category").change(function () {
var category = $("#category").val();
$.ajax({
url: "CreteProduct?handler=SubCategories",
method: "GET",
data: { category: category },
success: function (data) {
$("#subCategory option").remove();
$.each(data, function (index, itemData) {
$("#subCategory").append("<option value='" + itemData.Id + "'>" + itemData.Name + "</option>");
});
}
})
});
</script>
Result: The subcategory drop-down list is undefined. After selecting the category the number of items is good but displays 'undefined'.
You need to use itemData.value to replace itemData.Id,itemData.text to replace itemData.Name.Here is a demo worked:
cshtml.cs:
public class CreateProductModel : PageModel
{
[BindProperty]
public Product Product { get; set; }
public static List<ProductCategory> productCategories = new List<ProductCategory> { new ProductCategory { Id = 1, Name = "pc1" }, new ProductCategory { Id = 2, Name = "pc2" } };
public static List<ProductSubCategory> productSubCategories = new List<ProductSubCategory> { new ProductSubCategory { Id = 11, Name = "psc11", ProductCategoryId = 1 }, new ProductSubCategory { Id = 12, Name = "psc12", ProductCategoryId = 1 }, new ProductSubCategory { Id = 21, Name = "psc21", ProductCategoryId = 2 }, new ProductSubCategory { Id = 22, Name = "psc22", ProductCategoryId = 2 } };
public IActionResult OnGet()
{
ViewData["ProductCategoryId"] = new SelectList(productCategories, "Id", "Name");
ViewData["ProductSubCategoryId"] = new SelectList(productSubCategories, "Id", "Name");
return Page();
}
public JsonResult OnGetSubCategories(int category)
{
var subcategories = productSubCategories.Where(p => p.ProductCategoryId == category).ToList();
return new JsonResult(new SelectList(subcategories, "Id", "Name"));
}
}
cshtml:
<form method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Product.Name" class="control-label"></label>
<input asp-for="Product.Name" class="form-control" />
<span asp-validation-for="Product.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.Description" class="control-label"></label>
<input asp-for="Product.Description" class="form-control" />
<span asp-validation-for="Product.Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.ImagePath" class="control-label"></label>
<input type="file" asp-for="Product.ImagePath" class="form-control" name="image" onchange="readURL(this);" />
<span asp-validation-for="Product.ImagePath" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.DateOfNotification" class="control-label"></label>
<input asp-for="Product.DateOfNotification" class="form-control" />
<span asp-validation-for="Product.DateOfNotification" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Product.ProductCategoryId" class="control-label"></label>
<select id="category" asp-for="Product.ProductCategoryId" class="form-control" asp-items="ViewBag.ProductCategoryId"></select>
</div>
<div class="form-group">
<label asp-for="Product.ProductSubCategoryId" class="control-label"></label>
<select id="subCategory" asp-for="Product.ProductSubCategoryId" class="form-control" asp-items="ViewBag.ProductSubCategoryId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
#section scripts{
<script type="text/javascript">
$("#category").change(function () {
var category = $("#category").val();
$.ajax({
url: "CreateProduct?handler=SubCategories",
method: "GET",
data: {category: category },
success: function (data) {
$("#subCategory option").remove();
$.each(data, function (index, itemData) {
$("#subCategory").append("<option value='" + itemData.value + "'>" + itemData.text + "</option>");
});
}
})
});
</script>
}
result:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) mvc

I am inserting master and detail data using json function.
after inserting all data in the text box when I click save button then this
error show "500" and json return format is valid I already check json
format validation website. Now I am sharing json result you can see.
{"ItemCode":"001-0001","ItemDesc":"1","PackingDetail":"1","ReOrder_Lvl":"1","Curr_Qty":"1","Curr_Rate":"1","Curr_Value":"1","items":[{"Srno":"1","MUnitCode":"02","BasicUnit_Qty":"1","SaleRate":"1","TableName":"ItemMeasuring"},{"Srno":"1","God_ID":"2","Op_Qty":"1","Op_Amount":"1","TableName":"ItemOpening"}],"btnAddNew":"new"}
I am sharing everything means Controller code, HTML, javascript
function anyone tell me where I am wrong and what is the problem in my
code.
Controller
[HttpPost]
public ActionResult Items_Insert(string ItemCode, string ItemDesc, string PackingDetail, int ReOrder_Lvl, float Curr_Qty, float Curr_Rate, float Curr_Value, Items[] items, string btnAddNew)
{
string result = "Error! Order Is Not Complete!";
try
{
objclsItems.mItems_Insert(ItemCode, ItemDesc, PackingDetail, ReOrder_Lvl, Curr_Qty, Curr_Value, Curr_Rate, items, btnAddNew);
ViewBag.Message = "Your record has been inserted Successfully";
ModelState.Clear();
result = "Your record has been inserted Successfully!";
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
public int mItems_Insert(string ItemCode, string ItemDesc, string PackingDetail, int ReOrder_Lvl, float Curr_Qty, float Curr_Value, float Curr_Rate, Items[] items, string btnAddNew)
{
try
{
con.Open();
tr = con.BeginTransaction();
if (btnAddNew == "new")
cmd = new SqlCommand("Sp_ItemsInsert", con);
else
cmd = new SqlCommand("Sp_ItemsUpdate", con);
cmd.Parameters.AddWithValue("#ItemCode", ItemCode);
cmd.Parameters.AddWithValue("#Comp_Id", 1);
cmd.Parameters.AddWithValue("#ItemDesc", ItemDesc);
cmd.Parameters.AddWithValue("#PackingDetail", PackingDetail);
cmd.Parameters.AddWithValue("#ReOrder_Lvl", ReOrder_Lvl);
cmd.Parameters.AddWithValue("#Curr_Qty", Curr_Qty);
cmd.Parameters.AddWithValue("#Curr_Value", Curr_Value);
cmd.Parameters.AddWithValue("#Curr_Rate", Curr_Rate);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
if (items != null)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i].TableName == "ItemMeasuring")
{
if (btnAddNew == "new")
cmd = new SqlCommand("Sp_ItemMeasuringInsert", con);
else
cmd = new SqlCommand("Sp_ItemMeasuringUpdate", con);
cmd.Parameters.AddWithValue("#ItemCode", ItemCode);
cmd.Parameters.AddWithValue("#Comp_ID", 1);
cmd.Parameters.AddWithValue("#MUnitCode", items[i].MUnitCode);
cmd.Parameters.AddWithValue("#BasicUnit_Qty", items[i].BasicUnit_Qty);
cmd.Parameters.AddWithValue("#SaleRate", items[i].SaleRate);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
else if (items[i].TableName == "ItemOpening")
{
if (btnAddNew == "new")
cmd = new SqlCommand("Sp_ItemOpeningInsert", con);
else
cmd = new SqlCommand("Sp_ItemOpeningUpdate", con);
cmd.Parameters.AddWithValue("#ItemCode", ItemCode);
cmd.Parameters.AddWithValue("#Comp_ID", 1);
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#God_ID", items[i].God_ID);
cmd.Parameters.AddWithValue("#Op_Qty", items[i].Op_Qty);
cmd.Parameters.AddWithValue("#Op_Amount", items[i].Op_Amount);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
}
}
tr.Commit();
return i;
}
catch (SqlException sqlex)
{
tr.Rollback();
throw sqlex; // read all sql error
}
catch (Exception ex)
{
tr.Rollback();
throw ex; // General execption
}
finally
{
con.Close();
}
}
Model:
public string ItemCode { get; set; }
public int Comp_Id { get; set; }
public string ItemDesc { get; set; }
public string PackingDetail { get; set; }
public int ReOrder_Lvl { get; set; }
public float Curr_Qty { get; set; }
public float Curr_Value { get; set; }
public float Curr_Rate { get; set; }
public string MUnitCode { get; set; }
public float BasicUnit_Qty { get; set; }
public float SaleRate { get; set; }
public float Op_Qty { get; set; }
public float Op_Amount { get; set; }
public int God_ID { get; set; }
Javascript
<script>
//Show model
function addNewOrder() {
$("#ItemsNew").modal();
}
// Add Multiple Record (Item Measuring)
$("#addToListitemmeasureing").click(function (e) {
e.preventDefault();
if ($.trim($("#MUnitCode").val()) == "" || $.trim($("#BasicUnit_Qty").val()) == "" || $.trim($("#SaleRate").val()) == "") return;
var Srno = document.getElementById("detailsTableitemMeasuring").rows.length,
MUnitCode = $("#MUnitCode").val(),
BasicUnit_Qty = $("#BasicUnit_Qty").val(),
SaleRate = $("#SaleRate").val(),
detailsTableBodyMeasuring = $("#detailsTableitemMeasuring tbody");
var ItemsMeasuring = '<tr><td>' + Srno + '</td><td>' + MUnitCode + '</td><td>' + BasicUnit_Qty + '</td><td>' + SaleRate + '</td><td> <a data - itemId="0" href= "#" class="deleteItem" > Remove</a ></td ></tr > ';
detailsTableBodyMeasuring.append(ItemsMeasuring);
clearItemMeasuring();
});
// Add Multiple Record (Item Opening)
$("#addToListItemOpening").click(function (e) {
e.preventDefault();
if ($.trim($("#txtNGod_ID").val()) == "" || $.trim($("#Op_Qty").val()) == "" || $.trim($("#Op_Amount").val()) == "") return;
var Srno = document.getElementById("detailsTableItemOpening").rows.length,
God_ID = $("#txtNGod_ID").val(),
Op_Qty = $("#Op_Qty").val(),
Op_Amount = $("#Op_Amount").val(),
detailsTableItemOpening = $("#detailsTableItemOpening tbody");
var ItemsOpening = '<tr><td>' + Srno + '</td><td>' + God_ID + '</td><td>' + Op_Qty + '</td><td>' + Op_Amount + '</td><td> <a data-itemId="0" href = "#" class="deleteItem" > Remove</a ></td ></tr > ';
detailsTableItemOpening.append(ItemsOpening);
clearItemOpening();
});
//After Add A New Order In The List
function clearItemMeasuring() {
$("#MUnitCode").val('');
$("#BasicUnit_Qty").val('');
$("#SaleRate").val('');
}
function clearItemOpening() {
$("#txtNGod_ID").val('');
$("#Op_Qty").val('');
$("#Op_Amount").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove
$(document).on('click', 'a.deleteItem', function (e) {
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "white").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveItems(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "#Url.Action("Items_Insert")",
data: data,
success: function (result) {
JSON.parse(results);
location.reload();
},
fail: function (jqXHR, textStatus, errorThrown) {
console.log('Could not get posts, server response: ' + textStatus + ': ' + errorThrown);
}
}).responseJSON;
}
//Collect Multiple Order List For Pass To Controller (Item Measuring)
$("#btnsaveItemS").click(function (e) {
e.preventDefault();
var itemMeasuringArr = [];
itemMeasuringArr.length = 0;
$.each($("#detailsTableitemMeasuring tbody tr"), function () {
itemMeasuringArr.push({
Srno: $(this).find('td:eq(0)').html(),
MUnitCode: $(this).find('td:eq(1)').html(),
BasicUnit_Qty: $(this).find('td:eq(2)').html(),
SaleRate: $(this).find('td:eq(3)').html(),
TableName: 'ItemMeasuring'
});
});
$.each($("#detailsTableItemOpening tbody tr"), function () {
itemMeasuringArr.push({
Srno: $(this).find('td:eq(0)').html(),
God_ID: $(this).find('td:eq(1)').html(),
Op_Qty: $(this).find('td:eq(2)').html(),
Op_Amount: $(this).find('td:eq(3)').html(),
TableName: 'ItemOpening'
});
});
var data = JSON.stringify({
ItemCode: $("#txtNItemCode").val(),
ItemDesc: $("#txtNItemDesc").val(),
PackingDetail: $("#txtNPackingDetail").val(),
ReOrder_Lvl: $("#txtNReOrderLvl").val(),
Curr_Qty: $("#txtNCurrQty").val(),
Curr_Rate: $("#txtNCurrRate").val(),
Curr_Value: $("#txtNValue").val(),
items: itemMeasuringArr,
btnAddNew: $("#btnAddNew").val()
});
//Collect Multiple Order List For Pass To Controller (Item Opening)
$.when(saveItems(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
HTML:
<div class="tab-pane fade in show active" id="panel5" role="tabpanel">
<br>
<button type="button" id="btnAddNew" value="new" class="btn btn-primary" data-toggle="modal" data-target="#ItemsNew" style="float:left">Add New Items</button>
<div class="table-responsive">
<table id="jqGrid" class="table table-bordered table-striped"></table>
<div id="jqGridPager"></div>
</div>
<!--Add New Model Form-->
<div class="modal fade" id="ItemsNew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content" style="width:140%">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Add New Items</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<form id="NewOrdersss">
<div class="modal-body">
<div class="form-row">
<div class="col" id="poidd">
<!-- Purchase PO ID -->
<label for="lblItemCode">Item Category</label>
<div class="md-form">
#Html.DropDownListFor(m => m.CatCode, ViewBag.ItemCat as List<SelectListItem>, new { #class = "form-control mr-sm-3", id = "txtNCCode", Required = true })
</div>
</div>
<div class="col">
<label for="lblItemCode">Item Code</label>
<div class="md-form">
#Html.TextBox("ItemCode", (String)ViewBag.ItemCodeMaxNo, new { #class = "form-control mr-sm-3", #id = "txtNItemCode", Required = true, #Readonly=true })
</div>
</div>
<div class="col">
<label for="lblPackingDetail"> Item Description</label>
<div class="md-form">
#Html.TextBoxFor(m => m.ItemDesc, new { #class = "form-control", #id = "txtNItemDesc", Required = true })
</div>
</div>
<div class="col">
<label for="lblPackingDetail"> Packing Detail</label>
<div class="md-form">
#Html.TextBoxFor(m => m.PackingDetail, new { #class = "form-control", #id = "txtNPackingDetail", Required = true })
</div>
</div>
<div class="col">
<label for="lblRe-OrderLevel"> Re-Order Level</label>
<div class="md-form">
#Html.TextBoxFor(m => m.ReOrder_Lvl, new { #class = "form-control", #id = "txtNReOrderLvl", Required = true })
</div>
</div>
</div>
<div class="row">
<div class="column d-inline-block">
<h6 style="margin-top:10px;color:#ff6347">Stock on Hand</h6>
<div class="form-row">
<div class="col">
<div class="md-form">
#Html.TextBoxFor(m => m.Curr_Qty, new { #class = "form-control", #id = "txtNCurrQty", #placeholder = "" })
<label for="lblQuantity">Quantity</label>
</div>
</div>
<div class="col" style="margin-left:1.5%;">
<!-- SellerQuotRefNo -->
<div class="md-form">
#Html.TextBoxFor(m => m.Curr_Rate, new { #class = "form-control", #id = "txtNCurrRate", #placeholder = "" })
<label for="lblNRate">Rate</label>
</div>
</div>
<div class="col" style="margin-left:1.5%;">
<!--SellerQuotDate -->
<div class="md-form">
#Html.TextBoxFor(m => m.Curr_Value, new { #class = "form-control", #id = "txtNValue", #placeholder = "" })
<label for="lblNValue"> Value</label>
</div>
</div>
<br />
</div>
</div>
<div class="column">
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Item Measuring</h5>
<div class="form-row">
<!-- Requisition Date -->
<div class="col">
<label for="lbljob">Unit Description</label>
<div class="md-form">
#Html.DropDownListFor(m => m.MUnitCode, ViewBag.munit as List<SelectListItem>, new { #class = "chosen-select", id = "MUnitCode", Required = true })
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="BasicUnit_Qty" name="BasicUnit_Qty" placeholder="" class="form-control" />
<label for="lblQty">Qty</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="SaleRate" name="SaleRate" placeholder="" class="form-control" />
<label for="lblSaleRate">Sale Rate</label>
</div>
</div>
<div class="col-md-2 col-sm-offset-2">
<a id="addToListitemmeasureing" class="btn btn-primary">Add</a>
</div>
</div>
<table id="detailsTableitemMeasuring" class="table">
<thead style="background-color:#007bff; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Unit Description</th>
<th style="width:15%">Qty</th>
<th style="width:30%">Sale Rate</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Item Opening</h5>
<div class="form-row">
<!-- Requisition Date -->
<div class="col">
<label for="lbljob">Warehouse Description</label>
<div class="md-form">
#Html.DropDownListFor(m => m.God_ID, ViewBag.warehouse as List<SelectListItem>, new { #class = "chosen-select", id = "txtNGod_ID", Required = true })
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="Op_Qty" name="Op_Qty" placeholder="" class="form-control" />
<label for="lblOpeningQty">Opening Qty</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="Op_Amount" name="Op_Amount" placeholder="" class="form-control" />
<label for="lblOpeningAmount">Opening Amount</label>
</div>
</div>
<div class="col-md-2 col-sm-offset-2">
<a id="addToListItemOpening" class="btn btn-primary">Add</a>
</div>
</div>
<table id="detailsTableItemOpening" class="table">
<thead style="background-color:#007bff; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Warehouse Description</th>
<th style="width:15%">Opening Qty</th>
<th style="width:30%">Opening Amount</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
<div class="modal-footer">
<button type="reset" class="btn btn-primary" data-dismiss="modal">Close</button>
<button id="btnsaveItemS" type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
<!--/.Content-->
</div>
</div>
</div>
The type of all properties of JSON data have to corresponds the type of parameters of Items_Insert function to which you send the data. In your example, you send JSON data
{
"ItemCode": "001-0001",
"ItemDesc": "1",
"PackingDetail": "1",
"ReOrder_Lvl": "1",
"Curr_Qty": "1",
"Curr_Rate": "1",
"Curr_Value": "1",
"items": [{
"Srno": "1",
"MUnitCode": "02",
"BasicUnit_Qty": "1",
"SaleRate": "1",
"TableName": "ItemMeasuring"
}, {
"Srno": "1",
"God_ID": "2",
"Op_Qty": "1",
"Op_Amount": "1",
"TableName": "ItemOpening"
}],
"btnAddNew": "new"
}
where all properties are strings. On the other side you use
public ActionResult Items_Insert(string ItemCode, string ItemDesc, string PackingDetail,
int ReOrder_Lvl, float Curr_Qty, float Curr_Rate, float Curr_Value,
Items[] items, string btnAddNew)
and some other properties of Items, which are not strings too:
public float BasicUnit_Qty { get; set; }
public float SaleRate { get; set; }
public float Op_Qty { get; set; }
public float Op_Amount { get; set; }
public int God_ID { get; set; }
Thus you have to send another formatted data to the server or to change the type of some parameters and properties from int of float to string.
I remind that JSON serialization of numbers are not quoted numbers like 1 instead of "1".
To fix the problem on the client side you need to send the data like
{
"ItemCode": "001-0001",
"ItemDesc": "1",
"PackingDetail": "1",
"ReOrder_Lvl": 1,
"Curr_Qty": 1,
"Curr_Rate": 1,
"Curr_Value": 1,
"items": [{
"Srno": "1",
"MUnitCode": "02",
"BasicUnit_Qty": 1,
"SaleRate": 1,
"TableName": "ItemMeasuring"
}, {
"Srno": "1",
"God_ID": 2,
"Op_Qty": 1,
"Op_Amount": 1,
"TableName": "ItemOpening"
}],
"btnAddNew": "new"
}
Because of that you will need to add parseInt and parseFloat in some places of your JavaScript code. For example, you should use
...
God_ID: parseInt($(this).find('td:eq(1)').html(), 10),
Op_Qty: parseFloat($(this).find('td:eq(2)').html()),
...
instead of
...
God_ID: $(this).find('td:eq(1)').html(),
Op_Qty: $(this).find('td:eq(2)').html(),
...
used in your current code. You have to make close changes for all properties, which your interpret in your server code as float of integers instead of strings.

How can i set skip parameter on button click in Query?

I have a set of records in which i am applying skip and take parameters in Entity Framework .
So in query I set take parameters constant which is 10.
I want to change skip parameter dynamically on each button click.
this is my code.
public ActionResult DateRecords()
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
if (TempData["FromDate"] == null || TempData["toDate"] == null)
{
return View("InvalidDatesInput");
}
return View(this.GetRecordsByDate(0));
}
[HttpPost]
public ActionResult DateRecords(int skipParam)
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
return View(this.GetRecordsByDate(skipParam));
}
public PassengerPaging GetRecordsByDate(int skipParam)
{
string fDate = TempData["FromDate"].ToString();
string tDate = TempData["toDate"].ToString();
TempData.Keep();
PassengerPaging psngr = new PassengerPaging();
psngr.Passengers = repository.GetRecords(fDate, tDate, skipParam).Select(x => new ViewModel.Passenger
{
ID = x.ID,
Name = x.Name,
FlightNo = FlightRepos.SelectByID(x.FlightId).FlightNo,
Airline = airlineRepo.SelectByID(x.FlightId).Name,
SeatNo = x.SeatNo,
SequenceNo = x.SequenceNo,
Date = x.Date,
EnterBy = x.EnterBy,
CheckinTime = x.CheckinTime,
CheckoutTime = x.CheckoutTime,
IsCheckout = x.IsCheckout
}).ToList();
psngr.Count = repository.GetRecordss(fDate, tDate).Count();
psngr.skip = skipParam;
return psngr;
}
This is my Model.
public class PassengerPaging
{
[Key]
//public int ID { get; set; }
//public List<Passenger> Passengers { get; set; }
//public int CurrentPageIndex { get; set; }
//public int Count { get; set; }
public int ID { get; set; }
public List<Passenger> Passengers { get; set; }
public int skip { get; set; }
public int Count { get; set; }
}
This is my View
<div>
#using (Html.BeginForm("DateRecords", "PassengerInfo", FormMethod.Post))
{
<h2>All Records</h2>
<div class="inner_page_about">
</div>
<br />
<br />
<div class="w3-row w3-border" style="width:100%">
<div class="w3-container w3-half, col-md-4" >
<input type="button" class="btn btn-outline-success" onclick="location.href='#Url.Action("ExportToExcel", "PassengerInfo")'" value="Export Detail Data" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(false)" value="Month wise Graph" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(true)" value="Date wise Graph" />
</div>
</div>
<br />
<hr />
<table id="1">
<thead>
<tr>
<th>Name</th>
<th>Seat Number</th>
<th>Sequence Number</th>
<th>Airline</th>
<th>FLight Number</th>
<th>Date</th>
<th>CheckIn Time</th>
<th>Checkout Time</th>
<th>IsCheckout</th>
<th>Enter By</th>
</tr>
</thead>
#foreach (var item in Model.Passengers)
{
<tr>
<td>#item.Name</td>
<td>#item.SeatNo</td>
<td>#item.SequenceNo</td>
<td>#item.Airline</td>
<td>#item.FlightNo</td>
<td>#item.Date</td>
<td>#item.CheckinTime</td>
<td>#item.CheckoutTime</td>
<td>#item.IsCheckout</td>
<td>#item.EnterBy</td>
</tr>
}
</table>
<br />
<input type="button" id="1" value="next" onclick="PagerClick(#Model.skip)">
<input type="hidden" id="hfCurrentPageIndex" name="skip" />
#* <input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">*#
#*<td>
<input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">
</td>*#
<canvas id="graph" width="30" height="40" style="display:none"></canvas>
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript">
debugger;
function PagerClick(index) {
document.getElementById("hfCurrentPageIndex").value = index;
document.forms[0].submit();
}
Extra Information : This code is working fine but the prob is that if i have 100 records in my database it is showing 10 buttons as i put that type of logic , But i want only two buttons
Next
Previous
And on every click i want to add +10 on skip parameter initially it is 0
and on every click on Previous Button i want to -10 from skip parameter.

Categories