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
I am trying to build a form that will dynamically create readonly inputs using javascript and pass those values along with model values into the controller, but my FormCollection in my controller method only contains the model values, not the input values. Any help on what I am doing wrong would be awesome. Here is my code:
Model.Courses contains int CourseId and string CourseName. I am contructing readonly inputs with the value of the CourseName to pass into the FormCollection to establish the order of the courses contained within each bootcamp.
View:
<div class="container">
<div class="row">
<div class="col-xs-12">
<h2>Create Bootcamp</h2>
#using (Html.BeginForm("Create", "LMSBootcamp", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-xs-6 w-50">
<h5>Course Order</h5>
<ol id="orderContainer">
</ol>
</div>
<div class="col-xs-6 w-50">
<h5>Available Courses</h5>
<ul>
#foreach (var course in Model.Courses.OrderBy(a=>a.CourseName))
{
<li id="#course.CourseId" onclick="Add_Course()" data-arg="#course.CourseId">#course.CourseName</li>
}
</ul>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
<script type="text/javascript">
function Add_Course() {
var courseName = event.target.innerHTML;
var courseId = event.target.getAttribute('data-arg');
//create the readonly input for the course desired
var order = document.createElement("input");
order.readOnly = true;
order.setAttribute("type", "text");
order.setAttribute("value", courseName);
order.classList.add("form-control", "text-box", "single-line");
//create li element
var listElement = document.createElement("li");
listElement.onclick = function Remove_Course() {
var element = event.target
element.remove();
}
//add input to list element
listElement.appendChild(order);
//add list element to container
var orderContainer = document.getElementById("orderContainer");
orderContainer.appendChild(listElement);
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(FormCollection courseOrder)
{
return RedirectToAction("Index");
}
Thank you!
Before you submit make sure those dynamically added inputs have correct model names and you should be fine. So in you example it would be something similar to this:
<input type="text" name="courseName[0]" value="courseName 1"/>
<input type="text" name="courseName[1]" value="courseName 2"/>
<input type="text" name="courseName[3]" value="courseName 3"/>
And the model binder will automatically create a List of string with those 3 strings ("courseName 1","courseName 2","courseName 3") in them and assign it to the corresponding property, in this case value.
Here is a demo:
Models:
public class FormModel {
public string Title { get; set; }
public List<Course> Courses { get; set; }
}
public class Course {
public int CourseId { get; set; }
public string CourseName { get; set; }
}
View(before form submit add name to each input added):
#model FormModel
<div class="row">
<div class="col-xs-12">
<h2>Create Bootcamp</h2>
#using (Html.BeginForm("Create", "LMSBootcamp", FormMethod.Post, new { id = "myForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-xs-6 w-50">
<h5>Course Order</h5>
<ol id="orderContainer">
</ol>
</div>
<div class="col-xs-6 w-50">
<h5>Available Courses</h5>
<ul>
#foreach (var course in Model.Courses.OrderBy(a => a.CourseName))
{
<li id="#course.CourseId" onclick="Add_Course()" data-arg="#course.CourseId">#course.CourseName</li>
}
</ul>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
#section scripts{
<script type="text/javascript">
function Add_Course() {
var courseName = event.target.innerHTML;
var courseId = event.target.getAttribute('data-arg');
//create the readonly input for the course desired
var order = document.createElement("input");
order.readOnly = true;
order.setAttribute("type", "text");
order.setAttribute("value", courseName);
order.classList.add("form-control", "text-box", "single-line");
//create li element
var listElement = document.createElement("li");
listElement.onclick = function Remove_Course() {
var element = event.target
element.remove();
}
//add input to list element
listElement.appendChild(order);
//add list element to container
var orderContainer = document.getElementById("orderContainer");
orderContainer.appendChild(listElement);
}
//add name before form submit
$('#myForm').submit(function () {
var i = 0;
$("#orderContainer li").each(function () {
$(this).find("input").attr("name", "courseName[" + i+"]");
i++;
})
// DO STUFF...
return true; // return false to cancel form action
});
</script>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(FormCollection courseOrder)
{
return Ok();
}
result:
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.
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.
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>
}