I have following list view
Once I click Reject I just configured to open a modal dialog like following
So Once I submit this modal dialog I want to submit modal values to method to save that in database table.
this is relevant model classes
public class ProductViewModel
{
public AB_Product Products { get; set; }
public IEnumerable<AB_Product> LProducts { get; set; }
}
public partial class AB_Product
{
public string ProductID { get; set; }
public string ApprovalStatus { get; set; }
public string ReasonEn { get; set; }
public string ReasonAr { get; set; }
}
this is view page code
#model project_name.Models.ProductViewModel
<table class="table">
<tr>
<th>
Name
</th>
<th>
Action
</th>
</tr>
#foreach (var obj in Model.LProducts)
{
<tr>
#Html.HiddenFor(modelItem => obj.ProductID)
<td>
#Html.DisplayFor(modelItem => obj.ProductTitleEn)
</td>
<td>
<div class="btn-group btn-group-sm" id="CreateButton">
<button type="button" class="btn btn-default" onclick="location.href='#Url.Action("Create")';return false;">View Product</button>
</div>
#if (obj.ApprovalStatus == "Pending")
{
<div class="btn-group btn-group-sm" id="ApproveButton">
<button type="button" class="btn btn-success" onclick="location.href='#Url.Action("Change_Product_State","Home", new { productid = obj.ProductID, value = "Approved" },null)';return false;">Approve</button>
</div>
<div class="btn-group btn-group-sm" id="RejectButton">
<button type="button" id="modal-opener" class="btn btn-danger" return false;">Reject</button>
</div>
}
<div class="btn-group btn-group-sm" id="CreateButton">
<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("Create_ProductComments","Home", new { productid = obj.ProductID }, null)';return false;">Add Comments</button>
</div>
</td>
</tr>
}
</table>
<div id="dialog-modal" title="Basic modal dialog">
#using (Ajax.BeginForm("Change_Product_State", "Home", new { value = "Rejected" }, new AjaxOptions { UpdateTargetId = "ID", OnSuccess = "onSuccess" }))
{
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.Products.ReasonEn)
</div>
<div class="editor-field">
#Html.TextAreaFor(m => m.Products.ReasonEn)
#Html.ValidationMessageFor(m => m.Products.ReasonEn)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Products.ReasonAr)
</div>
<div class="editor-field">
#Html.TextAreaFor(m => m.Products.ReasonAr)
#Html.ValidationMessageFor(m => m.Products.ReasonAr)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</div>
}
</div>
#section Scripts
{
<script>
$(function () {
$("#dialog-modal").dialog({
autoOpen: false,
width: 400,
height: 400,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$("#modal-opener").click(function () {
$("#dialog-modal").dialog("open");
});
});
function onSuccess() {
$("#dialog-modal").dialog("close");
}
</script>
}
how to bind list object I click which is ProductID with m.Products.ProductID
Remove the #Html.HiddenFor(modelItem => obj.ProductID) from the foreach loop and inside the Ajax.BeginForm() add
#Html.HiddenFor(m => m.Products.ProductID)
so its value can be posted. Then add the value of the ProductID as a data- attribute of the button (and change the id to class - see notes below)
<button type="button" class="modal-opener btn btn-danger" data-id="#obj.ProductID">Reject</button>
and modify the script to
$(".modal-opener").click(function () { // use class name
$('#Products_ProductID').val($(this).attr("data-id")); // set the value of the hidden input
$("#dialog-modal").dialog("open");
})
Note that you have a lot of invalid html due to duplicate id attributes generated by your foreach loop. Use class names instead. Your html should be
#foreach (var obj in Model.LProducts)
{
<tr>
<td>#Html.DisplayFor(modelItem => obj.ProductTitleEn)</td>
<td>
<div class="btn-group btn-group-sm CreateButton"> // change
<button type="button" class="btn btn-default" onclick="location.href='#Url.Action("Create")';return false;">View Product</button>
</div>
#if (obj.ApprovalStatus == "Pending")
{
<div class="btn-group btn-group-sm ApproveButton"> // change
<button type="button" class="btn btn-success" onclick="location.href='#Url.Action("Change_Product_State","Home", new { productid = obj.ProductID, value = "Approved" },null)';return false;">Approve</button>
</div>
<div class="btn-group btn-group-sm RejectButton"> // change
<button type="button" class="modal-opener btn btn-danger" data-id="#obj.ProductID">Reject</button> // as above
</div>
}
<div class="btn-group btn-group-sm CreateButton"> // change
<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("Create_ProductComments","Home", new { productid = obj.ProductID }, null)';return false;">Add Comments</button>
</div>
</td>
</tr>
}
Related
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:
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。
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
};
I have a set of records in which i am applying skip and take parameters in Entity Framework .
So in query I set take parameters constant which is 10.
I want to change skip parameter dynamically on each button click.
this is my code.
public ActionResult DateRecords()
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
if (TempData["FromDate"] == null || TempData["toDate"] == null)
{
return View("InvalidDatesInput");
}
return View(this.GetRecordsByDate(0));
}
[HttpPost]
public ActionResult DateRecords(int skipParam)
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
return View(this.GetRecordsByDate(skipParam));
}
public PassengerPaging GetRecordsByDate(int skipParam)
{
string fDate = TempData["FromDate"].ToString();
string tDate = TempData["toDate"].ToString();
TempData.Keep();
PassengerPaging psngr = new PassengerPaging();
psngr.Passengers = repository.GetRecords(fDate, tDate, skipParam).Select(x => new ViewModel.Passenger
{
ID = x.ID,
Name = x.Name,
FlightNo = FlightRepos.SelectByID(x.FlightId).FlightNo,
Airline = airlineRepo.SelectByID(x.FlightId).Name,
SeatNo = x.SeatNo,
SequenceNo = x.SequenceNo,
Date = x.Date,
EnterBy = x.EnterBy,
CheckinTime = x.CheckinTime,
CheckoutTime = x.CheckoutTime,
IsCheckout = x.IsCheckout
}).ToList();
psngr.Count = repository.GetRecordss(fDate, tDate).Count();
psngr.skip = skipParam;
return psngr;
}
This is my Model.
public class PassengerPaging
{
[Key]
//public int ID { get; set; }
//public List<Passenger> Passengers { get; set; }
//public int CurrentPageIndex { get; set; }
//public int Count { get; set; }
public int ID { get; set; }
public List<Passenger> Passengers { get; set; }
public int skip { get; set; }
public int Count { get; set; }
}
This is my View
<div>
#using (Html.BeginForm("DateRecords", "PassengerInfo", FormMethod.Post))
{
<h2>All Records</h2>
<div class="inner_page_about">
</div>
<br />
<br />
<div class="w3-row w3-border" style="width:100%">
<div class="w3-container w3-half, col-md-4" >
<input type="button" class="btn btn-outline-success" onclick="location.href='#Url.Action("ExportToExcel", "PassengerInfo")'" value="Export Detail Data" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(false)" value="Month wise Graph" />
</div>
<div class="w3-container w3-half, col-md-4">
<input type="button" class="btn btn-outline-success" onclick="showGraph(true)" value="Date wise Graph" />
</div>
</div>
<br />
<hr />
<table id="1">
<thead>
<tr>
<th>Name</th>
<th>Seat Number</th>
<th>Sequence Number</th>
<th>Airline</th>
<th>FLight Number</th>
<th>Date</th>
<th>CheckIn Time</th>
<th>Checkout Time</th>
<th>IsCheckout</th>
<th>Enter By</th>
</tr>
</thead>
#foreach (var item in Model.Passengers)
{
<tr>
<td>#item.Name</td>
<td>#item.SeatNo</td>
<td>#item.SequenceNo</td>
<td>#item.Airline</td>
<td>#item.FlightNo</td>
<td>#item.Date</td>
<td>#item.CheckinTime</td>
<td>#item.CheckoutTime</td>
<td>#item.IsCheckout</td>
<td>#item.EnterBy</td>
</tr>
}
</table>
<br />
<input type="button" id="1" value="next" onclick="PagerClick(#Model.skip)">
<input type="hidden" id="hfCurrentPageIndex" name="skip" />
#* <input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">*#
#*<td>
<input type="Submit" class="btn btn-outline-success" value="FeedBack">
<a onclick="location.href='#Url.Action("CheckOutUpdate", "PassengerInfo", new { id = item.ID })'"> <input type="Submit" class="btn btn-outline-success" value="CheckOut"></a>
<input type="Submit" class="btn btn-outline-success" value="Update">
</td>*#
<canvas id="graph" width="30" height="40" style="display:none"></canvas>
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript">
debugger;
function PagerClick(index) {
document.getElementById("hfCurrentPageIndex").value = index;
document.forms[0].submit();
}
Extra Information : This code is working fine but the prob is that if i have 100 records in my database it is showing 10 buttons as i put that type of logic , But i want only two buttons
Next
Previous
And on every click i want to add +10 on skip parameter initially it is 0
and on every click on Previous Button i want to -10 from skip parameter.
I 'm newebie in Asp.net MVC 5
So , I have a simple project in which i'm usiong asp.net . I have an object named :
Object { Id, Code, Name} .
I want to list the Objects in grid , edit , add and remove .
I am able to show the list and add new object .
Those operations are in modal dialog .
I have some problems now :
How to send the Object to the action Controller then show it or edit itinto a modal dialog using javascript when i choose it ?
The second picture is when i click add new Object , it shows me the modal dialog , and all works fine with the Add , biut not with the others actions.
My Code
ObjectController :
public ActionResult AddObject()
{
if (Request.IsAjaxRequest())
return PartialView(dd);
return View(dd);
}
[HttpPost]
public ActionResult AddObject(ModelObject model)
{
/* Working Code */
}
AddObject partial View :
#using (Ajax.BeginForm("AddObject", "Object",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "msgAdd",
OnSuccess = "addSuccess",
OnFailure = "addFailure"
},
new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true);
<div class="row" style="padding: 5px 0 5px 0">
<div class="col-lg-12">
<div class="col-lg-12 border no-margin" style="padding:10px 0px 10px 0 !important">
<div class="form-group" style="align-content:center">
<label class="col-sm-4 control-label">Code </label>
<div class="col-lg-6">
#Html.TextBoxFor(m => m.Code, new { #class = "form-control", placeholder = "Code" })
#Html.ValidationMessageFor(m => m.Code)
</div>
<label class="col-sm-4 control-label">Libellé </label>
<div class="col-lg-6">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", placeholder = "Libellé " })
#Html.ValidationMessageFor(m => m.Name)
</div>
</div>
</div>
</div>
</div>
<div class="hr-line-solid no-margin"></div>
<div class="row" style="padding: 5px 0 5px 0">
<div class="col-sm-1 col-sm-offset-4">
<button type="reset" class="btn btn-outline btn-primary"><i class="icon-refresh icon-white"></i> Réinitialiser</button>
</div>
<div class="col-sm-3 col-sm-offset-4">
<button type="reset" class="btn btn-default right" data-dismiss="modal">Annuler</button>
<input type="submit" value="Enregistrer" class="btn btn-success right" />
</div>
</div>
<div id="msgAdd" style="display:none">
</div>
}
</div>
ListObjects View :
<tbody>
#foreach (var m in Model.objects)
{
<tr class="gradeX">
<td id="idObject" style="display:none;"><span class="hideextra">#m.Id</span></td>
<td><span class="hideextra">#m.Code</span></td>
<td><span class="hideextra">#m.Name</span></td>
<td class="infont">
<center>
<a id="btnEdit"><i class="fa fa-pencil-square-o text-"></i></a>
<i class="fa fa-trash-o text-danger"></i>
<i class="fa fa-search text-navy"></i>
</center>
</td>
</tr>
}
</tbody>
Javascript :
1- For adding :
$(document).ready(function () {
//jQuery.noConflict();
$("#btn").click(function () {
var url = "AddObject"; // the url to the controller
$.get(url, function (data) {
$("#saisieJDiag").draggable({
handle: ".modal-header"
});
$("#saisieJDiag").resizable();
$("#saisieJDiag").html(data);
$("#saisieJDiag").modal("show");
$('#saisieJDiag').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen();
});
$('.i-checks').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green',
});
});
});
});
</script>
Now I want the same approch but to edit and show the obecjt on the modal , how i can do that !