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。
Related
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.
Using MVC .NetCore, I populate a "partial" view and a Table. Within that table, a list of records.
Each row have a button to edit or delete. To delete a record, I need to have 4 IDs since the PK is made of those 4 keys.
I was able to make it work with a javascript, however, I do not like the "confirm" display being produce. I would like to have a more elegant way and use a modal form for this. But how do I retrieve the 4 values when clicking a button in of the row?
Here is a Row being populated from my Model:
<td>
<div>
<a onclick="showInPopup('#Url.Action("Match_StatsCreateOrEdit","Match_Stats",new {comp_id=item.Match_Stats.Comp_Id, team_id=item.Match_Stats.Team_Id,match_id=item.Match_Stats.Match_Id, match_Stat_Id=item.Match_Stats.Match_Stat_Id},Context.Request.Scheme)','Update A Stat')" class="btn btn-primary btn-xs"><i class="fas fa-pencil-alt"></i> Edit</a>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete</button>
</form>
</div>
</td>
Here is the Javascript currently used:
jQueryAjaxDelete = form => {
if (confirm('Are you sure want to delete this record ?')) {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
$('#view-all').html(res.html);
$.notify('Deleted Successfully !', {
globalPostion: 'Top Center',
className: 'success'
});
},
error: function (err) {
console.log(err)
}
})
} catch (ex) {
console.log(ex)
}
}
//prevent default form submit event
return false;
}
Here is the Model I would like to use. How do I get the 4 ID into this?
<!-- /.modal -->
<div class="modal fade" id="modal-removeplayers">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation needed</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this record ?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<!-- CODE HERE TO RETRIEVE All 4 IDs and Call the "delete" on the Controller -->>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
One way is that put the modal inside the loop:
Model:
public class Test
{
public Match_Stats Match_Stats { get; set; }
//other properties....
}
public class Match_Stats
{
public int Comp_Id { get; set; }
public int Team_Id { get; set; }
public int Match_Id { get; set; }
public int Match_Stat_Id { get; set; }
//other properties.....
}
View(Index.cshtml):
#model IEnumerable<Test>
#{
int i = 0;
}
#foreach (var item in Model)
{
//other code.....
<a onclick="showInPopup('#Url.Action("Match_StatsCreateOrEdit","Match_Stats",new {comp_id=item.Match_Stats.Comp_Id, team_id=item.Match_Stats.Team_Id,match_id=item.Match_Stats.Match_Id, match_Stat_Id=item.Match_Stats.Match_Stat_Id},Context.Request.Scheme)','Update A Stat')" class="btn btn-primary btn-xs"><i class="fas fa-pencil-alt"></i> Edit</a>
//add the button to launch the modal
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal-removeplayers_#i"><i class="fas fa-trash"></i> Delete</button>
<div class="modal fade" id="modal-removeplayers_#i">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation needed</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this record ?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
//move the form to here.....
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete</button>
</form>
</div>
</div>
</div>
</div>
i++; //add this...
}
Controller:
public IActionResult Index()
{
//hard-coded the data just for easy testing!!!
var model = new List<Test>()
{
new Test(){Match_Stats=new Match_Stats(){Comp_Id=1,Match_Id=11,Match_Stat_Id=12,Team_Id=13}},
new Test(){Match_Stats=new Match_Stats(){Comp_Id=2,Match_Id=21,Match_Stat_Id=22,Team_Id=23}},
new Test(){Match_Stats=new Match_Stats(){Comp_Id=3,Match_Id=31,Match_Stat_Id=32,Team_Id=33}}
};
return View(model);
}
[HttpPost]
public IActionResult Match_StatsDelete(int Comp_Id,int Match_Id, int Match_Stat_Id,int Team_Id)
{
//do your stuff.......
}
The second way, you can use partial view to reuse the modal and use ajax to invoke the partial view.
Model:
public class Test
{
public Match_Stats Match_Stats { get; set; }
//other properties....
}
public class Match_Stats
{
public int Comp_Id { get; set; }
public int Team_Id { get; set; }
public int Match_Id { get; set; }
public int Match_Stat_Id { get; set; }
//other properties.....
}
View(Index.cshtml):
#model IEnumerable<Test>
#foreach (var item in Model)
{
<a onclick="showInPopup('#Url.Action("Match_StatsCreateOrEdit","Match_Stats",new {comp_id=item.Match_Stats.Comp_Id, team_id=item.Match_Stats.Team_Id,match_id=item.Match_Stats.Match_Id, match_Stat_Id=item.Match_Stats.Match_Stat_Id},Context.Request.Scheme)','Update A Stat')" class="btn btn-primary btn-xs"><i class="fas fa-pencil-alt"></i> Edit</a>
<button type="button" class="btn btn-primary" onclick="toggleModal('#item.Match_Stats.Comp_Id','#item.Match_Stats.Team_Id','#item.Match_Stats.Match_Id','#item.Match_Stats.Match_Stat_Id')"><i class="fas fa-trash"></i> Delete</button>
}
<div id="loadModal">
<!--load the modal-->
</div>
#section Scripts
{
<script>
function toggleModal(comp_id,team_id,match_id,match_Stat_Id) {
var model = {
comp_id : comp_id,
team_id:team_id,
match_id:match_id,
match_Stat_Id:match_Stat_Id
};
$.ajax({
type: "Post",
url: "/Home/LoadPartial",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-removeplayers').modal('show')
}
})
}
</script>
}
Partial View in /Views/Shared folder(Partial.cshtml):
#model Match_Stats
<div class="modal fade" id="modal-removeplayers">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation needed</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this record ?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#Model.Comp_Id" asp-route-team_Id="#Model.Team_Id" asp-route-Match_Id="#Model.Match_Id"
asp-route-Match_Stat_Id="#Model.Match_Stat_Id" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete</button>
</form>
</div>
</div>
</div>
</div>
Controller:
public IActionResult Index()
{
//hard-coded the data just for easy testing!!!
var model = new List<Test>()
{
new Test(){Match_Stats=new Match_Stats(){Comp_Id=1,Match_Id=11,Match_Stat_Id=12,Team_Id=13}},
new Test(){Match_Stats=new Match_Stats(){Comp_Id=2,Match_Id=21,Match_Stat_Id=22,Team_Id=23}},
new Test(){Match_Stats=new Match_Stats(){Comp_Id=3,Match_Id=31,Match_Stat_Id=32,Team_Id=33}}
};
return View(model);
}
[HttpPost]
public IActionResult Match_StatsDelete(int Comp_Id,int Match_Id, int Match_Stat_Id,int Team_Id)
{
//do your stuff.......
}
[HttpPost]
public IActionResult LoadPartial(Match_Stats model)
{
//hard-coded the data just for easy testing!!!
var list = new List<Match_Stats>()
{
new Match_Stats(){Comp_Id=1,Match_Id=11,Match_Stat_Id=12,Team_Id=13},
new Match_Stats(){Comp_Id=2,Match_Id=21,Match_Stat_Id=22,Team_Id=23},
new Match_Stats(){Comp_Id=3,Match_Id=31,Match_Stat_Id=32,Team_Id=33}
};
var data = list.Where(a => a.Comp_Id == model.Comp_Id & a.Match_Id == model.Match_Id & a.Team_Id == model.Team_Id & a.Match_Stat_Id == model.Match_Stat_Id).FirstOrDefault();
return PartialView("Partial", data);
}
Result:
I have a Partial View as a Table, that will be refreshed with a Dropdown Selection in the Main View. This dropdown list includes company names. In the table below information matters pertaining to each company, and for each line of this information there is a drop-down list of all the functions that I can do with this line (like deleting or modifying the information) with a Pop-up Modal.
How can I call a Method in the main Model or Submit something? Or can I create a Partial View with Model in my Case?
Here is my Main View:
#page
#model Fachinformationsdienst_Kundenportal.Pages.Information_listModel
#{
}
<form>
<div class="form-row align-items-center">
<div class="form-group col-md-4">
<label for="inputState">Wählen Sie eine Unternehmen aus</label>
<select id="inputState" class="form-control">
#for (int i = 0; i < Model.companies.Count; i++)
{
<option>#Model.companies[i].FirmenKurzBezeichnung</option>
}
</select>
</div>
<div class="form-group col-md-6">
<input class="form-control" id="myInput" type="text" style="margin-top: 31px;" placeholder="Suche...">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-primary" style="margin-top: 31px;">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</form>
<div id="fachinfoContainer">
<partial name="_FachinfoPartial" model="#Model.myViewModel" />
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$("#inputState").change(function () {
var selectcompany = "";
if ($(this).val() != "Wählen Sie die Firma aus...") {
selectcompany = $(this).val();
}
$.ajax({
url: "/Actions/Information-List?handler=fachinfoPartial",
type: "Get",
data: { company: selectcompany },
success: function (result) {
$("#fachinfoContainer").html(""); //clear the fachinfo container.
$("#fachinfoContainer").html(result); //populate the container.
},
error: function (result) {
alert(result);
}
});
});
});
</script>
}
Here is my Partial View
#model Fachinformationsdienst_Kundenportal.Models.MyViewModel
<table class="table table-striped" id="FachinfoTable">
<thead>
<tr>
<th scope="col">Nr.</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Letzte Änderung</th>
<th scope="col">Aktuelle Version</th>
<th scope="col">Auftrag</th>
</tr>
</thead>
<tbody id="myTable">
#if (#Model.Fachinfos != null)
{
#for (int i = 0; i < #Model.Fachinfos.Count; i++)
{
<tr>
<th scope="row">#Model.Fachinfos[i].FachinfoNummer</th>
<td>#Model.Fachinfos[i].FachinfoName</td>
<td>#Model.Fachinfos[i].Status</td>
<td>#Model.Fachinfos[i].Datum</td>
<td>#Model.Fachinfos[i].PdfVersion</td>
<td>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#for (int c = 0; c < #Model.SelectedCompany.Permissions.Count; c++)
{
if (Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ERSTERFASSEN && Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ABFRAGEN)
{
<a class="dropdown-item" data-toggle="modal" data-number="#Model.Fachinfos[i].FachinfoNummer" data-version="#Model.Fachinfos[i].PdfVersion" data-target="##Model.SelectedCompany.Permissions[c]">#Model.SelectedCompany.Permissions[c]</a>
}
}
</div>
</div>
</td>
</tr>
}
}
</tbody>
</table>
<!-- The Delete Modal -->
<div class="modal fade" id="#Models.Company.Permission.LOESCHEN">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Bestätigen</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<span id="deletMessege">Sind Sie sicher, dass Sie diese Fachinformation löschen möchten?</span>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="confirm" type="submit" class="btn btn-primary">Senden</button>
</div>
</div>
</div>
</div>
<script>
$('##Models.Company.Permission.LOESCHEN').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var fiNumber = button.data('number') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('Fachinfonummer ' + fiNumber)
})
</script>
Here is my main model
using Fachinformationsdienst_Kundenportal.Classes;
using Fachinformationsdienst_Kundenportal.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Fachinformationsdienst_Kundenportal.Pages
{
public class Information_listModel : PageModel
{
public List<Company> companies { get; set; }
public List<Fachinfo> fachinfos = new List<Fachinfo>();
public MyViewModel myViewModel = new MyViewModel();
public void OnGet()
{
companies = APIRequester.GetCompanies(User.Identity.Name);
foreach (var company in companies)
{
fachinfos.AddRange(APIRequester.GetFachinfos(company.FirmenKurzBezeichnung));
}
}
public PartialViewResult OnGetFachinfoPartial(string company)
{
//based on the selctedcompany to filter data, then return to the partial view.
companies = APIRequester.GetCompanies(User.Identity.Name);
myViewModel = new MyViewModel()
{
SelectedCompany = companies.Find(r => r.FirmenKurzBezeichnung == company), //get the company object here
Fachinfos = APIRequester.GetFachinfos(company)
};
return Partial("_FachinfoPartial", myViewModel);
}
//Submit this Method from Partial view
public IActionResult onDelete(string fiNumber)
{
return Page();
}
}
}
You can use JQUERY AJAX calls for this
$.ajax({
type: "POST",
url: '/Information_listModel?handler=Ondelete',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data.result);
})
your method should return type IActionResult
I am junior (or less than junior) in IT. I have a problem with passing data from view to controller... What I want to achieve:
When user click:
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
I want pass whole object "Category" to controller (also with List Subcategory). Second button with id="addSubCategory" will add a field to enter the next subcategory, but I want to send everything after clicking the type = submit button. How can I pass all subcategories name to list and send one post method?
That is my View:
#model AplikacjaFryzjer_v2.Models.Category
#{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Subcategories"></label>
<input asp-for="Subcategories" />
<span asp-validation-for="Subcategories" class="text-danger"></span>
</div>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
</div>
</form>
My Action CreateCategory in controller:
[HttpPost]
public IActionResult CreateCategory(Category category)
{
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}
And my object (model):
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Subcategory> Subcategories {get;set;}
}
For submitting complex models, you need to ensure that the name attribute of these controls bound to the Subcategory class fields are displayed in the form of a collection index.
And trigger the addSubCategory click event in js to add Subcategory control and data.
Since you added model validation, I suggest you use ViewBag.Subcategories to save the Subcategories data that has been added to the current page to prevent data loss after clicking the validation.
And you only need to add an asp-validation-summary in your form. Since these fields belong to a model and are in a form, their error information will be counted in the asp-validation-summary div.
Here is a complete example:
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<Subcategory> Subcategories { get; set; }
}
public class Subcategory
{
[Required]
[DisplayName("Subcategory.Name")]
public string Name { get; set; }
}
Controller:
public IActionResult CreateCategory()
{
ViewBag.Subcategories = new List<Subcategory>() { };
return View();
}
[HttpPost]
public IActionResult CreateCategory(Category category)
{
if (!ModelState.IsValid)
{
// store Subcategories data which has been added
ViewBag.Subcategories = category.Subcategories == null ? new List<Subcategory>() { } : category.Subcategories;
return View("CreateCategory");
}
_categoriesRepository.AddCategory(category);
return RedirectToAction("ManageCategories");
}
View:
#model AplikacjaFryzjer_v2.Models.Category
#{
ViewData["Title"] = "Dodaj nową kategorię";
Layout = "~/Views/Shared/_Layout.cshtml";
var SubcategoriesData = (IList<AplikacjaFryzjer_v2.Models.Subcategory>)ViewBag.Subcategories;
}
<h1>Dodaj nową kategorię</h1>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Dodaj kategorię</button>
</div>
<div class="col-md-6 offset-6">
#for (int i = 0; i < SubcategoriesData.Count(); i++)
{
<div class="form-group">
<label>Name#(i)</label>
<input asp-for="Subcategories[i].Name" value="#SubcategoriesData[i].Name" />
<span asp-validation-for="Subcategories[i].Name" class="text-danger"></span>
</div>
}
<button class="btn btn-primary" onclick="RemoveSubcategory(this)" id="removeSubcategory">remove</button>
<button class="btn btn-primary" id="addSubCategory" value="table">Dodaj podkategorię</button>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</form>
#section Scripts
{
<script>
var i = #SubcategoriesData.Count()-1;
$(document).ready(function () {
if (#SubcategoriesData.Count() <= 0) {
$("#removeSubcategory").hide();
}
$("#addSubCategory").click(function (e) {
e.preventDefault();
i++;
var name = '<label>Name' + i + '</label><input name = "Subcategories[' + i + '].Name" type="text"/>';
$("#removeSubcategory").before('<div class="form-group">' + name + '</div>');
$("#removeSubcategory").show();
});
});
function RemoveSubcategory(btn) {
event.preventDefault();
$(btn).prev("div").remove();
i--;
if (i == #SubcategoriesData.Count() -1) {
$("#removeSubcategory").hide();
}
}
</script>
}
Here is test result:
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
};