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.
Related
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
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; }
}
I am junior (or less than junior) in IT. I have a problem with passing data from view to controller... What I want to achieve:
When user click:
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
I want pass whole object "Category" to controller (also with List Subcategory). Second button with id="addSubCategory" will add a field to enter the next subcategory, but I want to send everything after clicking the type = submit button. How can I pass all subcategories name to list and send one post method?
That is my View:
#model AplikacjaFryzjer_v2.Models.Category
#{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Subcategories"></label>
<input asp-for="Subcategories" />
<span asp-validation-for="Subcategories" class="text-danger"></span>
</div>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
</div>
</form>
My Action CreateCategory in controller:
[HttpPost]
public IActionResult CreateCategory(Category category)
{
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}
And my object (model):
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Subcategory> Subcategories {get;set;}
}
For submitting complex models, you need to ensure that the name attribute of these controls bound to the Subcategory class fields are displayed in the form of a collection index.
And trigger the addSubCategory click event in js to add Subcategory control and data.
Since you added model validation, I suggest you use ViewBag.Subcategories to save the Subcategories data that has been added to the current page to prevent data loss after clicking the validation.
And you only need to add an asp-validation-summary in your form. Since these fields belong to a model and are in a form, their error information will be counted in the asp-validation-summary div.
Here is a complete example:
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<Subcategory> Subcategories { get; set; }
}
public class Subcategory
{
[Required]
[DisplayName("Subcategory.Name")]
public string Name { get; set; }
}
Controller:
public IActionResult CreateCategory()
{
ViewBag.Subcategories = new List<Subcategory>() { };
return View();
}
[HttpPost]
public IActionResult CreateCategory(Category category)
{
if (!ModelState.IsValid)
{
// store Subcategories data which has been added
ViewBag.Subcategories = category.Subcategories == null ? new List<Subcategory>() { } : category.Subcategories;
return View("CreateCategory");
}
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}
View:
#model AplikacjaFryzjer_v2.Models.Category
#{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";
var SubcategoriesData = (IList<AplikacjaFryzjer_v2.Models.Subcategory>)ViewBag.Subcategories;
}
<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
#for (int i = 0; i < SubcategoriesData.Count(); i++)
{
<div class="form-group">
<label>Name#(i)</label>
<input asp-for="Subcategories[i].Name" value="#SubcategoriesData[i].Name" />
<span asp-validation-for="Subcategories[i].Name" class="text-danger"></span>
</div>
}
<button class="btn btn-primary" onclick="RemoveSubcategory(this)" id="removeSubcategory">remove</button>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</form>
#section Scripts
{
<script>
var i = #SubcategoriesData.Count()-1;
$(document).ready(function () {
if (#SubcategoriesData.Count() <= 0) {
$("#removeSubcategory").hide();
}
$("#addSubCategory").click(function (e) {
e.preventDefault();
i++;
var name = '<label>Name' + i + '</label><input name = "Subcategories[' + i + '].Name" type="text"/>';
$("#removeSubcategory").before('<div class="form-group">' + name + '</div>');
$("#removeSubcategory").show();
});
});
function RemoveSubcategory(btn) {
event.preventDefault();
$(btn).prev("div").remove();
i--;
if (i == #SubcategoriesData.Count() -1) {
$("#removeSubcategory").hide();
}
}
</script>
}
Here is test result:
I am trying to filter my table by element.data. I have a dropdown list for the user to select the value and a submit button once they have finished. The table gets the initial data but when I select a value and click submit I get all of the values. The filter is not working at all.
Javascript filter
$('#Product').on('change', function () {
var count = 0;
var value = this.value;
$('#results-tbody tr').each(function () {
var element = $(this);
element.data('filters', element.data('filters').replace(/dropdown/g, ''));
if (value !== 'All' && element.data("product").indexOf(value) === -1) {
element.data('filters', element.data('filters') + 'dropdown');
}
count = count + hideOrShow(element);
});
setResultsCount(count);
});
$('#Changes').on('change', function () {
var count = 0;
var value = this.value;
$('#results-tbody tr').each(function () {
var element = $(this);
element.data('filters', element.data('filters').replace(/dropdown/g, ''));
if (value !== 'All' && element.data("oc").indexOf(value) === -1) {
element.data('filters', element.data('filters') + 'dropdown');
}
count = count + hideOrShow(element);
});
setResultsCount(count);
});
Report Table Page
var productList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Flexitouch", Value = "Flexitouch"},
new SelectListItem {Text = "ACTitouch", Value = "ACTitouch"},
new SelectListItem {Text = "Entre", Value = "Entre"},
}, "Text", "Value");
var showList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Changes Only", Value = "Changes Only"},
new SelectListItem {Text = "Referrals Only", Value = "Referral Only"},
}, "Text", "Value");
<div class="layout clinics">
#using (Html.BeginForm("AccountSummaryReport", "Reports",
FormMethod.Post))
{
#Html.ValidationSummary(false)
<div style="border-bottom:1px solid #bbb">
<h1>Account Summary Report</h1>
</div>
<!--<div class="filter-btns top">
<h4 class="filter-heading">Quick Search By</h4>
<input type="button" name="all" class="button1 filter-button active" value="All" />
<input type="button" name="flexitouch" class="button1 filter-button" value="Flexitouch" />
<input type="button" name="actitouch" class="button1 filter-button" value="ACTitouch" />
<input type="button" name="entre" class="button1 filter-button" value="Entre" />
</div>-->
<fieldset class="form-wrapper form-side-labels form-labels-125 search-box-center">
<div class="form-field form-full">
<!-- New Dropdown ! -->
<div class="editor-label">
<label>#Html.DisplayNameFor(model => model.Product)</label>
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Product, productList, "All", new { #class = "css-class clinic-dropdown" })
</div>
</div>
<div class="form-field form-full">
<div class="editor-label">
<label>#Html.DisplayNameFor(model => model.Changes)</label>
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Changes,showList, "All", new { #class = "css-class clinic-dropdown" })
</div>
</div>
<div class="form-field">
<input name="SearchButton" type="submit" value="Search" />
</div>
</fieldset>
<table class="table results-table">
<tr>
<th><i id="count"> (#ViewBag.Count found) </i></th>
</tr>
<tbody id="results-tbody">
#foreach (var item in Model.SearchResults)
{
<tr class="table__row-link" data-patientname"="#item.PatientLastName , #item.PatientLastName"
data-product="#item.Product" data-referral="#item.d_Order_Date" data-oc="#item.d_Order_Complete_Date"
data-approved="#item.ApprovedDate" data-inactive="#item.d_Inactive_Date" data-training="#item.LastTrainedDate" data-links="#item.Links" data-filters="none">
<td>
<a href="#Url.Action("Details", "Patient", new { patientID = item.PT_RecID })">
<strong>#Html.DisplayFor(modelItem => item.PatientLastName, item.PatientFirstName) (#Html.DisplayFor(modelItem => item.PT_RecID))</strong>
<br />
<strong>Product: </strong>#Html.DisplayFor(modelItem => item.Product)
<br />
<strong>Referral: </strong>#Html.DisplayFor(modelItem => item.d_Order_Date)
<br />
<strong>OC: </strong> #Html.DisplayFor(modelItem => item.d_Order_Complete_Date)
<br />
<strong>Shipped: </strong> #Html.DisplayFor(modelItem => item.d_Ship_Date)
<br />
<strong>Approved: </strong> #Html.DisplayFor(modelItem => item.ApprovedDate)
<br />
<strong>Inactive: </strong> #Html.DisplayFor(modelItem => item.d_Inactive_Date)
<br />
<strong>Training: </strong> #Html.DisplayFor(modelItem => item.LastTrainedDate)
<br />
<strong>Links: </strong> #Html.DisplayFor(modelItem => item.Links)
<br />
</a>
</td>
</tr>
}
</tbody>
</table>
Model
public class AccountSummaryReportModel
{
public string Product { get; set; }
public string Clinic_RecID { get; set; }
public IEnumerable<v_Report_AccountSummary> SearchResults { get; set; }
public string SearchButton { get; set; }
public IEnumerable<SelectListItem> Changes { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Start")]
//[DataType(DataType.Date)]
public DateTime Start { get; set; }
}
You have the event listener "$('#Product').on('change'....", however I don't see a control with the id="Product". I suspect that is your issue. You'll need to assign that id to the control you're looking to fire on change.
I believe you have the same issue with your $('#Changes') event listener as well.
I have following list view
Once I click Reject I just configured to open a modal dialog like following
So Once I submit this modal dialog I want to submit modal values to method to save that in database table.
this is relevant model classes
public class ProductViewModel
{
public AB_Product Products { get; set; }
public IEnumerable<AB_Product> LProducts { get; set; }
}
public partial class AB_Product
{
public string ProductID { get; set; }
public string ApprovalStatus { get; set; }
public string ReasonEn { get; set; }
public string ReasonAr { get; set; }
}
this is view page code
#model project_name.Models.ProductViewModel
<table class="table">
<tr>
<th>
Name
</th>
<th>
Action
</th>
</tr>
#foreach (var obj in Model.LProducts)
{
<tr>
#Html.HiddenFor(modelItem => obj.ProductID)
<td>
#Html.DisplayFor(modelItem => obj.ProductTitleEn)
</td>
<td>
<div class="btn-group btn-group-sm" id="CreateButton">
<button type="button" class="btn btn-default" onclick="location.href='#Url.Action("Create")';return false;">View Product</button>
</div>
#if (obj.ApprovalStatus == "Pending")
{
<div class="btn-group btn-group-sm" id="ApproveButton">
<button type="button" class="btn btn-success" onclick="location.href='#Url.Action("Change_Product_State","Home", new { productid = obj.ProductID, value = "Approved" },null)';return false;">Approve</button>
</div>
<div class="btn-group btn-group-sm" id="RejectButton">
<button type="button" id="modal-opener" class="btn btn-danger" return false;">Reject</button>
</div>
}
<div class="btn-group btn-group-sm" id="CreateButton">
<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("Create_ProductComments","Home", new { productid = obj.ProductID }, null)';return false;">Add Comments</button>
</div>
</td>
</tr>
}
</table>
<div id="dialog-modal" title="Basic modal dialog">
#using (Ajax.BeginForm("Change_Product_State", "Home", new { value = "Rejected" }, new AjaxOptions { UpdateTargetId = "ID", OnSuccess = "onSuccess" }))
{
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.Products.ReasonEn)
</div>
<div class="editor-field">
#Html.TextAreaFor(m => m.Products.ReasonEn)
#Html.ValidationMessageFor(m => m.Products.ReasonEn)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Products.ReasonAr)
</div>
<div class="editor-field">
#Html.TextAreaFor(m => m.Products.ReasonAr)
#Html.ValidationMessageFor(m => m.Products.ReasonAr)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</div>
}
</div>
#section Scripts
{
<script>
$(function () {
$("#dialog-modal").dialog({
autoOpen: false,
width: 400,
height: 400,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$("#modal-opener").click(function () {
$("#dialog-modal").dialog("open");
});
});
function onSuccess() {
$("#dialog-modal").dialog("close");
}
</script>
}
how to bind list object I click which is ProductID with m.Products.ProductID
Remove the #Html.HiddenFor(modelItem => obj.ProductID) from the foreach loop and inside the Ajax.BeginForm() add
#Html.HiddenFor(m => m.Products.ProductID)
so its value can be posted. Then add the value of the ProductID as a data- attribute of the button (and change the id to class - see notes below)
<button type="button" class="modal-opener btn btn-danger" data-id="#obj.ProductID">Reject</button>
and modify the script to
$(".modal-opener").click(function () { // use class name
$('#Products_ProductID').val($(this).attr("data-id")); // set the value of the hidden input
$("#dialog-modal").dialog("open");
})
Note that you have a lot of invalid html due to duplicate id attributes generated by your foreach loop. Use class names instead. Your html should be
#foreach (var obj in Model.LProducts)
{
<tr>
<td>#Html.DisplayFor(modelItem => obj.ProductTitleEn)</td>
<td>
<div class="btn-group btn-group-sm CreateButton"> // change
<button type="button" class="btn btn-default" onclick="location.href='#Url.Action("Create")';return false;">View Product</button>
</div>
#if (obj.ApprovalStatus == "Pending")
{
<div class="btn-group btn-group-sm ApproveButton"> // change
<button type="button" class="btn btn-success" onclick="location.href='#Url.Action("Change_Product_State","Home", new { productid = obj.ProductID, value = "Approved" },null)';return false;">Approve</button>
</div>
<div class="btn-group btn-group-sm RejectButton"> // change
<button type="button" class="modal-opener btn btn-danger" data-id="#obj.ProductID">Reject</button> // as above
</div>
}
<div class="btn-group btn-group-sm CreateButton"> // change
<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("Create_ProductComments","Home", new { productid = obj.ProductID }, null)';return false;">Add Comments</button>
</div>
</td>
</tr>
}