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.
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:
im trying to post to mvc.core controller textarea value & id value & im getting js error "result is not defined "
and the only data the controller getting the id value .
Razor:
<div class="well">
<div class="row">
<form asp-action="AddToSellList" method="post" class="form-horizontal shadow" style="padding: 10px;">
#foreach (var item in Model)
{
<div class="well well-sm" style="background-color: white;">
<div class=" row">
<div class="col-sm-10 pull-right text-right">
#* Prop *#
#foreach (var qestion in item.QAViewModel)
{
<div id="#item.Id" class="collapse" style="background-color: gray">
<p>Qestion</p>
#* Prop *#
#foreach (var ansewr in qestion.Answers)
{
#* Prop *#
}
</div>
}
</div>
<div class="col-sm-2">
<button class="btnShowModal btn btn-primary btnWhiteSpace" id="#item.Id" type="button" value="#item.Id">
#item.Id
<i class="fas fa-info-circle" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="##item.Id"> <i class="fas fa-question-circle" aria-hidden="true"></i>Bla bla </button>
</div>
</div>
</div>
//Check box for selecting items for Action AddToSellList
<input type="checkbox" name="Hiden" value="#item.Id"/>
}
<button type="submit" id="btt"> submit to Action AddToSellList</button>
</form>
</div>
</div>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm ">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<i class="fas fa-window-close"></i>
</button>
<h4 class="modal-title">moder for posting for _AskQ </h4>
</div>
<div class="modal-body ">
<form asp-action="_AskQ" class="form-horizontal" style="padding: 10px; " method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" name="id" asp-for="#Model.First().SiteUserId" />
<div class="form-group">
<textarea name="Question" type="text" class="abc form-control text-right"id="a" required=""> </textarea>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Ask</button>
</div>
</form>
</div>
</div>
</div>
</div>
Js:`
<script type="text/javascript">
$(document).ready(function() {
$('.collapse').on('shown.bs.collapse',
function() {
$(".collapse").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".btnShowModal").click(function() {
$("#loginModal").modal('show');
var id = $(this).attr("id");
//$(".button4").click(function(e) {
// e.preventDefault();
$(".button4").click(function() {
url = '#Url.Action("_AskQ", "Bid")';
const value = $.trim($("textarea").val());
if (value === "") {
alert(value);
}
var data = {
Id: id,
value: value
};
console.log(id);
console.log(value);
$.ajax({
url: url,
data: data,
type: "POST"
}).done(function(result) {
$(id).html(result);
}).fail(function(x, s, e) {
alert("failed: " + s);
});
});
}
);
});
`
controller :
[HttpPost]
public IActionResult _AskQ(QAViewModel Vm)
{
if (!ModelState.IsValid)
{
return View(Vm);
}
var qustion = new QuoteQuestion
{
SiteUserId = _userManager.GetUserId(User),
QuoteId = Vm.Id,
Question = Vm.Question
};
_context.quoteQuestions.Add(qustion);
_context.SaveChanges();
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
ViewBag.q = qustion.Question;
ViewBag.Id = qustion.QuoteId;
ViewBag.SiteUId = qustion.SiteUserId;
}
return RedirectToAction("Index");
}
public class QAViewModel
{
public int QuoteQuestionId { get; set; }
public int Id { get; set; }
public string Question { get; set; }
public string SiteUserId { get; set; }
public virtual IList<Answers> Answers { get; set; }
}
In the data after ajax call, I can see the Id value & the Value value, but it keep failing to actually post to the controller (Id value only).
I'm posting from ActionResult name :index to ActionResult name _AskQ
Try the following changes in your code ,pay attention to the passed data name should be consistent with the parameter in the action
$(".button4").click(function() {
const value = $.trim($("textarea").val());
if (value === "") {
alert(value);
}
var Vm = {
Id: id,
Question: value
};
console.log(id);
console.log(value);
$.ajax({
type: "POST",
url: "/Bid/_AskQ",
contentType: "application/json",
data: "json",
data: JSON.stringify(Vm),
success: function (result) {
$(id).html(result);
},
error: function (x, s, e) {
alert("failed: " + s);
}
});
});
Add the [FromBody] attribute on the parameter when passing the json type data
[HttpPost]
public IActionResult _AskQ([FromBody]QAViewModel Vm)
Then the return value of the _AskQ method should be the html json result that you want to render the place with the specify id .Make the modification according to your needs。
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.