To my ASP.NET MVC web application, I'm trying to apply a full calendar with create and view events.
For that, I found this amazing tutorial on here and I followed same.
All parts are working as same as the tutorial.
But when I try to create an event, for the controller it won't pass the selected date Start and EndDate to the controller. Other data comes to the controller but the dates are not passing.
I tried in the script checking by console log and I found that the date values are written on the console when I hit submit. But only the dates are not passing.
Can you help me to find the error here?
This is the View
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Save Event</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
This is the Script
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
EventID: $('#hdEventID').val(),
Subject: $('#txtSubject').val().trim(),
Start: $('#txtStart').val().trim(),
End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
Description: $('#txtDescription').val(),
ThemeColor: $('#ddThemeColor').val(),
IsFullDay: $('#chkIsFullDay').is(':checked')
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
This is the model
public partial class EventsMain
{
[Key]
public int Id { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime Start_Date { get; set; }
public DateTime? End_Date { get; set; }
public bool IsFullDay { get; set; }
public string Theme_Color { get; set; }
public int Create_By { get; set; }
public DateTime Created_Date { get; set; } = DateTime.Now;
}
Controller
public JsonResult SaveEvent(EventsMain e)
{
var status = false;
if (e.Id > 0)
{
//Update the event
var v = db.EventsMain.Where(a => a.Id == e.Id).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
e.Create_By = int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
db.EventsMain.Add(e);
}
db.SaveChanges();
status = true;
return new JsonResult { Data = new { status = status } };
}
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.
Hello i am using MVC 5 c# with ado net code , i am inserting master data and master detail data when i insert data and click save all then event fire but value not pass to controller obj show null value , i try a lot but i could not find problem that's why i am sharing code and help senior people maybe you could understand better and easy find problem. i am sharing javascript code view code and controller code function code . when i debug javascript code i did not find any problem in javascript and there is no error in javascript code .
View
<main class="pt-5 mx-lg-5">
<div class="container-fluid mt-5">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_content">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body" style="background-color:#F0FFFF">
<button type="button" id="btnAddnew" class="btn btn-primary" data-toggle="modal" data-target="#centralModalLGInfoDemo" style="float:right">Add New</button>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr No</th>
<th>Item Desc</th>
<th>Qty</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Requisitions)
{
<tr>
<td>#Html.DisplayFor(module => item.Srno)</td>
<td>#Html.DisplayFor(module => item.ItemDesc)</td>
<td>#Html.DisplayFor(modelItem => item.Qty)</td>
<td>#Html.DisplayFor(modelItem => item.Remarks)</td>
<td>
<a onclick="GetDetails(#item.ReqNo)">
<i class="fa fa-edit"></i>
</a>
<a>
#Html.ActionLink(" ", "DeleteCustomer", "Home", new { id = item.ReqNo }, new { onclick = "return confirm('Are sure wants to delete?');", #class = "fa fa-trash-o" })
</a>
</td>
</tr>
}
</tbody>
<tfoot>
</tfoot>
</table>
</div>
</div>
</div>
<!---End-->
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<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 Requisition</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="NewOrderForm">
<div class="modal-body">
<div class="form-row">
<div class="col">
<!-- Requisition Date -->
<div class="md-form">
#Html.TextBox("ReqNo", (String)ViewBag.ReqNo, new { #class = "form-control mr-sm-3", #id = "txtRequisitionno" })
<label for="lblRequisition">Requisition No.</label>
</div>
</div>
<div class="col">
<!-- Requisition Date -->
<div class="md-form">
#Html.TextBoxFor(m => m.ReqDate, new { #class = "form-control", #id = "txtRequisitionDatepicker" })
<label for="lblRequisitionDatepicker">Requisition Date</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Job, new { #class = "form-control", #id = "txtjob" })
<label for="lbljob">Job</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Approvedby, new { #class = "form-control", #id = "txtApprovedby" })
<label for="lblApprovedby">Approved by</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<div class="custom-control custom-checkbox">
<span style="float:right">
#Html.CheckBoxFor(m => m.IsApproved, new { #class = "custom-control-input", #id = "defaultChecked2" })
<label class="custom-control-label" for="defaultChecked2">Approved</label>
</span>
</div>
</div>
</div>
</div>
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Requisition Details</h5>
<hr />
<div>
<div class="form-row">
<div class="col-md-1">
<!-- Requisition Date -->
<div class="md-form">
<input type="text" id="SrNo" name="SrNo" placeholder="Srno" class="form-control" />
<label for="lblSrno">Sr No.</label>
</div>
</div>
<div class="col-md-4">
<!-- Requisition Date -->
<div class="md-form">
#Html.DropDownListFor(m => m.ItemCode, ViewBag.Items as List<SelectListItem>, new { #class = "form-control", id = "txtItemcode" })
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="Qty" name="Qty" placeholder="Qty" class="form-control" />
<label for="lbljob">Qty</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="text" id="Reemarks" name="Reemarks" placeholder="Remarks" class="form-control" />
<label for="lblRemarks">Remarks</label>
</div>
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">Add To List</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead style="background-color:#33b5e5; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Items</th>
<th style="width:15%">Qty</th>
<th style="width:30%">Remarks</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveRequisition" type="submit" class="btn btn-danger">Save Order</button>
</div>
</div>
</form>
</div>
<!--/.Content-->
</div>
</div>
</div>
</main>
javascript
<script>
//Show model
function addNewOrder()
{
$("#NewOrderForm").modal();
}
// Add Multiple Record
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#SrNo").val()) == "" || $.trim($("#txtItemcode").val()) == "" || $.trim($("#Qty").val()) == "" || $.trim($("#Reemarks").val()) == "") return;
var Srno = $("#SrNo").val(),
items = $("#txtItemcode").val(),
qty = $("#Qty").val(),
remark = $("#Reemarks").val(),
detailsTableBody = $("#detailsTable tbody");
var ReqItems = '<tr><td>' + Srno + '</td><td>' + items + '</td><td>' + qty + '</td><td>' + remark + '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(ReqItems);
clearItem();
//After Add A New Order In The List
function clearItem()
{
$("#SrNo").val('');
$("#txtItemcode").val('');
$("#Qty").val('');
$("#Reemarks").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 saveRequisition(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Home/RequisitionInsert", // function save
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveRequisition").click(function (e)
{
e.preventDefault();
var requisitionArr = [];
requisitionArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
requisitionArr.push({
Srno: $(this).find('td:eq(0)').html(),
items: $(this).find('td:eq(1)').html(),
qty: $(this).find('td:eq(2)').html(),
remark: $(this).find('td:eq(3)').html(),
});
});
var data = JSON.stringify({
txtRequisitionno: $("#txtRequisitionno").val(),
txtRequisitionDatepicker: $("#txtRequisitionDatepicker").val(),
txtjob: $("#txtjob").val(),
txtApprovedby: $("#txtApprovedby").val(),
defaultChecked2: $("#defaultChecked2").val(),
item: requisitionArr
});
$.when(saveRequisition(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
});
</script>
Controller
[HttpPost]
public ActionResult RequisitionInsert(Requisition objModel, List<Requisition> oblist)
{
try
{
int result = objclsRequisition.RequisitionInsert(objModel, oblist);
if(result==1)
{
ViewBag.Message = "Your record has been inserted Successfully";
ModelState.Clear();
}
else
{
ViewBag.Message = "Unsucessfull";
ModelState.Clear();
}
return RedirectToAction("Requisition", "Home");
}
catch (Exception)
{
throw;
}
}
Function
public int RequisitionInsert(Requisition Req, List<Requisition> objlist)
{
try
{
con.Open();
tr = con.BeginTransaction();
cmd = new SqlCommand("Sp_RequisitionMainInsert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ReqNo", Req.ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#ReqDate", Req.ReqDate.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Job", Req.Job);
cmd.Parameters.AddWithValue("#ApprovedBy", Req.Approvedby);
cmd.Parameters.AddWithValue("#UserName", System.Web.HttpContext.Current.Session["AgentName"]);
cmd.Parameters.AddWithValue("#IsApproved", Req.IsApproved);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
for (int i = 0; i < objlist.Count; i++)
{
cmd = new SqlCommand("Sp_RequisitionDetailInsert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ReqNo", Req.ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#SrNo", Req.Srno);
cmd.Parameters.AddWithValue("#ItemCode", Req.ItemCode);
cmd.Parameters.AddWithValue("#Qty", Convert.ToDecimal(Req.Qty));
cmd.Parameters.AddWithValue("#Remarks", Req.Remarks);
}
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();
}
}
The issue lays in the api model definition.
You have declared your methods parameters as this
[HttpPost]
public ActionResult RequisitionInsert(Requisition objModel, List<Requisition> oblist)
But, when posting data in MVC you can only have one input model as that model will be parsed straight from the complete request body.
To solve this, create a request model where you define the properties to read from the body.
public class RequestModel
{
public string TxtRequisitionno { get; set; }
public string TxtRequisitionDatepicker { get; set; }
public string Txtjob { get; set; }
public string TxtApprovedby { get; set; }
public string DefaultChecked2 { get; set; }
public List<Requisition> Items { get; set; }
}
And then use it
[HttpPost]
public ActionResult RequisitionInsert(RequestModel model)
NOTE: I have declared the properties in the RequestModel as the same you try to send from the client
Your client model:
{
txtRequisitionno: $("#txtRequisitionno").val(),
txtRequisitionDatepicker: $("#txtRequisitionDatepicker").val(),
txtjob: $("#txtjob").val(),
txtApprovedby: $("#txtApprovedby").val(),
defaultChecked2: $("#defaultChecked2").val(),
item: requisitionArr
};