Get items from a DevExpress ListBox using JavaScript - javascript

Im creating two DevExpress ListBox to set a relation between products and clients.
See Moving Items between List Boxes
So:
My Controller C#
public ActionResult ReglaCreate()
{
if (Authentication.User.Identity.IsAuthenticated)
{
Service service= new Service();
var articulos = service.GetArt();
var locales = service.GetLoc();
Session["Articulos"] = articulos;
Session["Locales"] = locales;
return View();
}
else
return RedirectToAction("Login", "Account");
}
DevExpress ListGrid
<div class="wrapper wrapper-content animated fadeInRight" id="ReglaCreateController" ng-controller="ReglaController">
<div class="row">
<div class="ibox-content">
<form class="form-horizontal">
<div class="form-group" style="width:50%">
<label class="col-lg-2 control-label" style="float:left">Nombre</label>
<textarea style="font-size:15px;text-align:left;width:350px;height:40px;margin-left:15px;" class="control-label" id="lblNombreRegla">{{lblNombreRegla}}</textarea>
</div>
</form>
<br />
<div class="form-group">
<div class="col-md-4" style="width:17.5%">
<span style="float:right"><label class="col-lg-2 control-label" style="width:180px">Locales disponibles</label></span>
</div>
<div class="col-md-4" style="padding-left: 495px">
<span style="float:left"><label class="col-lg-2 control-label" style="width:180px">Locales elegídos</label></span>
</div>
</div>
<table style="height">
<tr>
<td>
#Html.DevExpress().ListBox(settings =>
{
settings.Name = "lbAvailableLocales";
settings.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
var locales = (List<LocalViewModel>)Session["Locales"];
foreach (var local in locales)
{
settings.Properties.Items.Add(local.Nombre, local.ID);
}
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s, e) { UpdateButtonStateLocales(); }";
settings.Properties.EnableClientSideAPI = true;
settings.Width = System.Web.UI.WebControls.Unit.Pixel(350);
settings.Height = System.Web.UI.WebControls.Unit.Pixel(200);
}).GetHtml()
</td>
<td style="padding: 60px">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveSelectedItemsToRightLocales";
settings.Text = "Agregar >";
settings.ClientSideEvents.Click = "function(s, e) { AddSelectedItemsLocales(); }";
}).GetHtml()
</div>
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveAllItemsToRightLocales";
settings.Text = "Agregar todos >>";
settings.ClientSideEvents.Click = "function(s, e) { AddAllItemsLocales(); }";
}).GetHtml()
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveSelectedItemsToLeftLocales";
settings.Text = "< Eliminar";
settings.ClientSideEvents.Click = "function(s, e) { RemoveSelectedItemsLocales(); }";
}).GetHtml()
</div>
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveAllItemsToLeftLocales";
settings.Text = "<< Eliminar todos";
settings.ClientSideEvents.Click = "function(s, e) { RemoveAllItemsLocales(); }";
}).GetHtml()
</div>
</div>
</div>
</td>
<td>
#Html.DevExpress().ListBox(settings =>
{
settings.Name = "lblChoosenLocales";
settings.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e) { UpdateButtonStateLocales(); }";
settings.Properties.EnableClientSideAPI = true;
settings.Width = System.Web.UI.WebControls.Unit.Pixel(350);
settings.Height = System.Web.UI.WebControls.Unit.Pixel(200);
}).GetHtml()
</td>
</tr>
</table>
<br />
<div class="form-group">
<div class="col-md-4" style="width:17.5%">
<span style="float:right"><label class="col-lg-2 control-label" style="width:180px">Artículos disponibles</label></span>
</div>
<div class="col-md-4" style="padding-left: 495px">
<span style="float:left"><label class="col-lg-2 control-label" style="width:180px">Artículos elegídos</label></span>
</div>
</div>
<table>
<tr>
<td>
#Html.DevExpress().ListBox(settings =>
{
settings.Name = "lbAvailable";
settings.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
var articulos = (List<ArticuloViewModel>)Session["Articulos"];
foreach (var articulo in articulos)
{
settings.Properties.Items.Add(articulo.Nombre, articulo.ID);
}
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s, e) { UpdateButtonState(); }";
settings.Properties.EnableClientSideAPI = true;
settings.Width = System.Web.UI.WebControls.Unit.Pixel(350);
settings.Height = System.Web.UI.WebControls.Unit.Pixel(200);
}).GetHtml()
</td>
<td style="padding: 60px">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveSelectedItemsToRight";
settings.Text = "Agregar >";
settings.ClientSideEvents.Click = "function(s, e) { AddSelectedItems(); }";
}).GetHtml()
</div>
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveAllItemsToRight";
settings.Text = "Agregar todos >>";
settings.ClientSideEvents.Click = "function(s, e) { AddAllItems(); }";
}).GetHtml()
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveSelectedItemsToLeft";
settings.Text = "< Eliminar";
settings.ClientSideEvents.Click = "function(s, e) { RemoveSelectedItems(); }";
}).GetHtml()
</div>
<div class="col-md-4">
#Html.DevExpress().Button(settings =>
{
settings.Name = "btnMoveAllItemsToLeft";
settings.Text = "<< Eliminar todos";
settings.ClientSideEvents.Click = "function(s, e) { RemoveAllItems(); }";
}).GetHtml()
</div>
</div>
</div>
</td>
<td>
#Html.DevExpress().ListBox(settings =>
{
settings.Name = "lblChoosen";
settings.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e) { UpdateButtonState(); }";
settings.Properties.EnableClientSideAPI = true;
settings.Width = System.Web.UI.WebControls.Unit.Pixel(350);
settings.Height = System.Web.UI.WebControls.Unit.Pixel(200);
}).GetHtml()
</td>
</tr>
</table>
</div>
#*<br />*#
<div style="float:right">
<input class="btn btn-sm btn-primary" type="submit" name="btnGuardar" id="btnGuardar" value="Crear" ng-click="Guardar()" />
</div>
</div>
My controllers JS:
$scope.Guardar = function () {
if (confirm('¿Está seguro de guardar los datos?')) {
$("#btnGuardar").prop('disabled', 'disabled');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
var nombreRegla = $("#lblNombreRegla").val();
var localesEnGrilla = $("#lblChoosenLocales").val();
var articulosEnGrilla = $("#lblChoosen").val();
//some code here
$http({
method: 'POST',
url: baseURL + 'Configuracion/CrearRegla/?Nombre=' + nombreRegla + "&Locales="+ localesEnGrilla + "&Articulos="+ articulosEnGrilla,
}).success(function (result) {
if (result != null) {
$("#btnGuardar").prop('disabled', '');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
$scope.volver();
}
}).error(function (data, status, headers, config) {
$("#btnGuardar").prop('disabled', '');
alert(data);
$scope.MostrarMensajeOk = false;
$scope.MostrarGrilla = false;
$('html, body').animate({ scrollTop: 0 }, 'slow');
});
};
};
What i need its get all selected items from both list, to save in my database and then work it. What can i do? Is this posible? I've trying a lot of solutions but nothing works.

Use the client-side ASPxClientListBox.GetSelectedValues method for this purpose:
#Html.DevExpress().ListBox(settings => {
settings.Name = "lblChoosenLocales";
}).GetHtml()
var selectedValues = lblChoosenLocales.GetSelectedValues();
alert(selectedValues);

Related

How to avoid getting plain JSON result in ASP.NET MVC 5

I have a view that has a button for applying for a job, and this button is redirected to a HttpPost action method that handles the apply logic and then returns a JSON result to the same view. as shown below:
// POST: Application/Apply
[HttpPost]
public ActionResult Apply(string idUser, int idAnnouncement)
{
try
{
// TODO: Add insert logic here
// Search for the candidate that has the same Hash code as idUser param
Candidate appliedCandidate = db.Candidates.Where(c => c.CandidateSecondID.Equals(idUser)).FirstOrDefault();
// todo: check if Candidate is already applyed to job
var check = db.Applications.Where(a => a.CandidateID.Equals(appliedCandidate.CandidateID) && a.AnnouncementID.Equals(idAnnouncement)).FirstOrDefault();
if (check == null)
{
Application newApp = new Application
{
AnnouncementID = idAnnouncement,
CandidateID = appliedCandidate.CandidateID,
ApplicationDate = DateTime.Now,
};
db.Applications.Add(newApp);
db.SaveChanges();
return this.Json(new
{
EnableSuccess = true,
SuccessTitle = "Success",
SuccessMsg = "Your application has been sent successfully!"
});
}
else
{
return this.Json(new
{
EnableSuccess = false,
ErrorTitle = "Warning",
ErrorMsg = "You are already applayed for this Job!"
});
}
}
catch
{
return View();
}
}
Here is the AJAX call:
$.ajax({
method: "POST",
url: action,
success: function (result) {
if (result.EnableSuccess) {
swal(
result.SuccessTitle,
result.SuccessMsg,
'success'
)
} else {
swal(
result.ErrorTitle,
result.ErrorMsg,
'warning'
)
}
},
error: function (err) {
console.log(err);
}
})
and here is the full view :
#model IEnumerable<JobPostingProject.Models.Announcement>
#using Microsoft.AspNet.Identity;
#using Microsoft.AspNet.Identity.Owin;
#{
ViewBag.Title = "List of jobs";
}
#using (Html.BeginForm("Index", "Announcement", FormMethod.Get))
{
<div class="row mb-3">
<div class="col-lg-3 ">
<div class="title">
<i class="fas fa-search mr-2"></i>
<input type="text" name="titleInput" class="title__input form-control border-0" placeholder="Job Title" value="#ViewBag.Job" />
</div>
</div>
<div class="col-lg-3">
<div class="city">
<i class="fas fa-map-marker-alt mr-2"></i>
<input type="text" name="cityInput" class="city__input form-control border-0" placeholder="Location" value="#ViewBag.City" />
</div>
</div>
<div class="col-lg-3">
<div class="categorie">
#Html.DropDownList("Categories", null, "Job Category", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row my-4">
<div class="col-lg-3">
<div class="date mb-4">
#*<i class="fas fa-search mr-2"></i>*#
<input type="date" name="dateInf" class="title__input form-control" style="border: 1px solid #ced4da; padding-left: 10px;" />
</div>
</div>
<div class="col-lg-3">
<div class="date mb-4">
#*<i class="fas fa-search mr-2"></i>*#
<input type="date" name="dateSup" class="title__input form-control" style=" border: 1px solid #ced4da;
padding-left: 10px;
" />
</div>
</div>
<div class="col-lg-3">
<div class="level">
#Html.DropDownList("Levels", ViewBag.Levels as SelectList, "Level", new { #class = "form-control" })
</div>
</div>
</div>
<div class="search">
<input type="submit" value="Search" class="text-white text-decoration-none btn btn-primary search__button" />
#*#Html.ActionLink("Search", "Index", "Announcement", null, new { #class = "text-white text-decoration-none btn btn-primary search__button" })*#
</div>
}
<!--list of all jobs searched for-->
<div class="container mt-5">
#{
if (!Model.Any())
{
<p class="text-center p-3 text-secondary">No job found with the chosen critiria</p>
}
else
{
<p class="text-secondary">#ViewBag.TotalResults job results found</p>
foreach (var item in Model)
{
<div class="row">
<div class="col-lg-7">
<div class="jobs">
#using (Html.BeginForm("Apply", "Application", new { idUser = User.Identity.GetUserId(), idAnnouncement = item.AnnouncementID }, FormMethod.Post, new { #class = "w-100 AnnonceForm" }))
{
<div class="job">
<div class="job__header d-flex align-items-center justify-content-between flex-wrap mb-0">
<h5 class="job__title">#item.Title</h5>
<h2 class="job__city">#item.Location</h2>
</div>
<h5 class="job__datetime">Posted in #item.PublicationDate.ToString("dd/mm/yyyy")</h5>
<h5 class="job__company-name mb-4">By #item.Company.Name</h5>
<div class="job__actions d-flex align-items-center">
<p class="job__apply my-0 mr-2">
#Html.ActionLink("More details", "AnnouncementDetails", "Application", new { idAnnouncement = item.AnnouncementID }, new { #class = "btn btn-primary" })
</p>
#if (!User.IsInRole("Company"))
{
<input type="submit" value="Apply Now" class="btn btn-outline-primary submit-btn">
}
</div>
</div>
}
</div>
</div>
<div class="col-lg-5"></div>
</div>
}
}
}
</div>
#section AnnouncementIndex {
<link href="#Url.Content("~/Content/Home.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Announcement/AnnouncementIndex.css")" rel="stylesheet" type="text/css" />
}
#section Scripts{
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
let submitButtons = document.querySelectorAll(".submit-btn");
for (let i = 0; i < submitForms.length; i++) {
submitButtons[i].addEventListener("submit", e => {
e.preventDefault();
var el = this.parentElement;
while (el.className != 'AnnonceForm') {
el = el.parentElement;
}
//el is now your parent
let action = el.attr("action");
$.ajax({
method: "POST",
url: action,
data: {},
dataType: "json",
success: function (result) {
console.log("entered success block");
if (result.EnableSuccess) {
swal(
result.SuccessTitle,
result.SuccessMsg,
'success'
)
} else {
swal(
result.ErrorTitle,
result.ErrorMsg,
'warning'
)
}
},
error: function (err) {
console.log(err);
}
})
return false;
})
}
</script>
}
BUT, for some reason, I get this plain JSON result instead of actually returning to the success function in the AJAX call.

pass data of input "hidden" in modal mvc 5

I'm a new mvc developper, I make a list in my controller, my view show this list and for each row i have a button for a modal view.I want to pass the data of the ViewBag in my list according for each row in my modal.
This is my modal html:
<div class="modal" id="addBadgetoStudentModal-#item.ID" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg animated bounceInDown">
<div class="modal-content">
#using (Html.BeginForm("AddBadgeToStudent", "Badges", new { ID = item.ID }, FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="modal-header">
<h4 class="modal-title">Badges</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="">
<div class="row">
#if (ViewBag.Badges != null)
{
for (var i = 0; i < ViewBag.Badges.Count; i++)
{
<div class="col-lg-3 col-sm-6 col-md-4">
<div class="team-member ">
<div class="row margin-0">
<div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
<img src="#ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
</div>
<div class="team-info" style="text-align:center; width:100%;">
#ViewBag.Badges[i].Label
<br />
<input id="Badge_#ViewBag.Badges[i].ID" class="checkBoxBadgeClass" type="checkbox" />
</div>
</div>
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<i class="fa fa-plus-circle"></i> #Resource.Add
</div>
}
</div>
</div>
</div>
<a class="fa fa-pencil-alt" data-toggle="modal" href="#addBadgetoStudentModal-#item.ID" onclick="btnModal()"></a>
This is my List Html View:
#foreach (var item in Model)
{
<tr id="#item.ID">
<td style="text-align:center; width:5%;">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td style="text-align: center; width:25%;">
#item.FullName
</td>
<td style="width:450px;">
#for (var i = 0; i < item.BadgesAssigned.Count; i++)
{
<img src="#item.BadgesAssigned[i].ImageUrl" width="50" title="#item.BadgesAssigned[i].Name" style="float:left;" />
}
<input type="hidden" id="studentBadges_#item.ID" value="#String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))"/>
</td>
}
and this my controller to get my student list and in another table get the badge assigned to a student, so in the list view the student can have 20 badges/25:
public ActionResult BadgeManagement(int? CohortId, int? id)
{
ViewBag.CohortId = db.Cohorts.Select(p => new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString()
});
if (CohortId != null ? CohortId > 0 : false)
{
var cs = db.CohortSubscriptions.Where(student => student.CohortId == CohortId).Include(c => c.Cohorts).Include(c => c.Registrations);
List<BadgesByStudentViewModel> badgesByStudentList = new List<BadgesByStudentViewModel>();
foreach (var student in cs) {
badgesByStudentList.Add(new BadgesByStudentViewModel
{
ID = student.ID,
FullName = student.Registrations.FullName,
BadgesAssigned = db.Enrolled_Students_Badges.Where(x => x.CohortSubscriptionId == student.ID).Select(x => new BadgesAssigned
{
ID = x.ID,
Name = x.Label,
ImageUrl = x.ImageURL
}).ToList()
});
}
ViewBag.Badges = db.Badges.ToList();
return View(badgesByStudentList.ToList());
}
return View(new List<BadgesByStudentViewModel>());
}
I found my solution
This is my html:
<tbody>
#foreach (var item in Model)
{
<tr id="#item.ID">
<td style="text-align:center; width:5%;">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td style="text-align: center; width:25%;">
#item.FullName
</td>
<td style="width:450px;">
#for (var i = 0; i < item.BadgesAssigned.Count; i++)
{
<img src="#item.BadgesAssigned[i].ImageUrl" width="50" title="#item.BadgesAssigned[i].Name" style="float:left;" />
}
</td>
<td style="text-align:center; width:5%;">
<button style="border:none;background: transparent;" data-studentid="#item.ID" data-studentname="#item.FullName" data-badges="#String.Join(",", item.BadgesAssigned.Select(x => x.ID.ToString()))" data-toggle="modal" data-target="#addBadgetoStudentModal" class="modalLink"><i class="fa fa-pencil-alt"></i></button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal" id="addBadgetoStudentModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg animated bounceInDown">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Badges</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="">
<u>#Resource.AddBadgeToStudent:</u>
<br />
<br />
<div class="row">
#if (ViewBag.Badges != null)
{
for (var i = 0; i < ViewBag.Badges.Count; i++)
{
<div class="col-lg-3 col-sm-6 col-md-4">
<div class="team-member ">
<div class="row margin-0">
<div class="team-info" style="text-align:center; border: 1.2pt solid #1874BF;">
<img src="#ViewBag.Badges[i].ImageURL" style="width:80%;" class="img-fluid" />
</div>
<div class="team-info" style="text-align:center; width:100%;">
#ViewBag.Badges[i].Label
<br />
<input id="Badge_#ViewBag.Badges[i].ID" data-badgeid="#ViewBag.Badges[i].ID" data-label="#ViewBag.Badges[i].Label" class="checkBoxBadgeClass" type="checkbox" />
</div>
</div>
</div>
</div>
}
}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<i class="fa fa-plus-circle"></i> #Resource.Edit
</div>
</div>
</div>
</div>
and this is my jquery:
currentStudentId = null;
currentAssignedBadge = [];
$('#BadgeAssignmentTable').dataTable({
responsive: true,
aLengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"]
]
});
$(".modalLink").on("click", function () {
var $pencil = $(this);
var studentId = $pencil.data('studentid');
var badges = $pencil.data('badges');
var studentName = $pencil.data("studentname");
PrepareBadgesModal(studentId, badges.split(","), studentName);
});
PrepareBadgesModal = function (studentId, assignedBadges, studentName) {
currentStudentId = studentId;
console.log(assignedBadges);
currentAssignedBadge = [];
$.each(assignedBadges, function (k, v) { return currentAssignedBadge.push(parseInt(v, 10)); });
$.each(assignedBadges, function (k, v) {
var $badge = $("#Badge_" + v);
$badge.prop("checked", true);
var label = $badge.data("label");
$badge.on("click", function (event) {
var res = ConfirmRemoveBadge($(this), label, studentName);
event.stopPropagation();
});
});
}
ConfirmRemoveBadge = function ($badge, label, studentName) {
var txt = "ATTENTION\r\rÊtes-vous certain de vouloir retirer le badge \"" + label + "\" à " + studentName + "?";
var r = confirm(txt);
if (r == true) {
$badge.prop("checked", false);
$badge.unbind("click");
} else {
$badge.prop("checked", true);
}
}
$("#AssignBadges").click(function () {
ModifyBadgesAction();
});
ModifyBadgesAction = function (badgeList) {
var selBadgeLst = $('input[id^=Badge_]:checked').map(function (k, v) { return parseInt($(v).data('badgeid'), 10); });
//TODO: Close the modal
var removedLst = $.grep(currentAssignedBadge, function (v, k) {
return $.grep(selBadgeLst, function (vv, kk) {
return v == vv;
}).length == 0;
});
var AddedList = $.grep(selBadgeLst, function (v, k) {
return $.grep(currentAssignedBadge, function (vv, kk) {
return v == vv;
}).length == 0;
});
var jsonData = JSON.stringify({ studentId : currentStudentId, AddedList: AddedList, removedLst: removedLst });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Badges/ModifyBadgesAction',
data: jsonData,
success: function (data, textStatus, jqXHR) {
//console.log(data, textStatus, jqXHR);
if (data.code == 0) {
ApplyBadgeActionSuccess(data);
}
else {
ApplyBadgeActionError(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
ApplyBadgeActionError({ code: jqXHR.status, message: "Technical Error", data: [{ jqXHR: jqXHR, error: errorThrown }] });
}
});
};
ApplyBadgeActionSuccess = function (data) {
alert(data.message);
window.location.reload(true);
}
ApplyBadgeActionError = function (data) {
alert(data.message);
}

value not pass from view to controller in mvc

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
};

Dynamic add field using nested accordion

Good Day!
I'm working on my project right now and I need to dynamically add form when button click. I have a nested accordion and inside the accordion is ng-select. To make it clear this is my code
<div class="box box-default" *ngFor="let form of forms; let form_array_index = index">
<div class="box-header with-border text-center">
<h3 class="box-title">
<div class="row">
<div class="col-md-4">
<select2 id="segment" name="segment"
[data]="add_segment"
[width]="293"
[value]="segment_value"
(valueChanged)="changedSegment($event, form_array_index)"
required>
</select2>
</div>
</div>
</h3>
<div class="box-tools pull-right">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-2">
<label for="category">Values:</label>
<select2 id="category" name="category"
[options]="options"
[data]="add_category"
[width]="293"
[value]="category_value"
(valueChanged)="changedCategory($event, form_array_index)"
required>
</select2>
</div>
</div>
<div class="box-header with-border text-center" *ngIf="cat_value">
<div class="panel panel-default">
<div class="panel-heading">
<h5 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion1" href="#{{ category_current[form_array_index] }}">{{collection_category[form_array_index].category}}
</a>
</h5>
</div>
<div id="{{ category_current[form_array_index] }}" class="panel-collapse collapse">
<div class="panel-body">
<div class="panel-body">
<button class="btn btn-success btn-xs pull-left" (click)="addQuestions()">Add Question</button>
<div class="row" >
<select2 *ngIf="query" id="question" name="question"
[data]="add_question"
[width]="293"
[value]="question_value"
(valueChanged)="changedQuestion($event)"
required>
</select2>
</div>
<button class="btn btn-success btn-xs pull-left" (click)="addSubCat()">Add Sub Category</button>
<div class="row" >
<select2 *ngIf="subcat" id="subcategory" name="subcategory"
[options]="options"
[data]="add_subcategory"
[width]="293"
[value]="subcategory_value"
(valueChanged)="changedSubcategory($event, form_array_index)"
required>
</select2>
</div>
<div class="panel-group" id="accordion21" *ngIf="subcat">
<ul class="list-group">
<li class="list-group-item" >
<div class="panel">
<a data-toggle="collapse" data-parent="#accordion21" href="#{{ subcategory_current }}" >
<strong>{{ get_subcategory }} </strong>
</a>
<div id="{{subcategory_current}}" class="panel-collapse collapse">
<div class="panel-body">
<label for="question">Question:</label>
<select2 id="question" name="question"
[data]="add_question"
[width]="293"
[value]="question_value"
(valueChanged)="changedQuestion($event)"
required>
</select2> <br>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div></div>
</div>
<div class="box-tools pull-right">
</div>
</div>
</div>
This means in SEGMENT it can have multiple CATEGORY and inside category it can have a question or they they Choose SUB CATEGORY and they have to choose a question
This is my component.ts
public collection_category = [];
public collection_subcategory = [];
addSegment(){
this._q_service.addSegment().
subscribe(
data => {
this.add_segment = Array.from(data);
let id = 0;
let text = 'Select Segment';
this.add_segment.unshift({id,text});
// this.segment_value = [];
this.segment_current = this.segment_value;
},
err => console.error(err)
);
}
changedSegment(data: any, form_array_index: any) {
this.segment_current = data.value;
if(this.segment_current.length > 0){
for (let i = 0; i < this.add_segment.length; ++i) {
if (this.add_segment[i].id == this.category_current) {
this.collection_category[form_array_index].segment = this.add_segment[i].text;
}
}
}
console.log('segment', this.collection_category);
}
addCategory(){
this._q_service.addCategory().
subscribe(
data => {
this.add_category = Array.from(data);
this.category_value = [];
this.options = {
multiple: true
}
let id = 0;
let text = 'Select Category';
this.add_category.unshift({id,text});
this.category_value = [];
// this.category_current.push(this.category_value);
// console.log(this.category_current);
},
err => console.error(err)
);
}
changedCategory(data: any, form_array_index: any ) {
this.category_current = data.value;
if(this.category_current.length > 0){
let len = this.add_category.length;
for (let i = 0; i < len; ++i) {
if (this.add_category[i].id == this.category_current) {
this.get_category = this.add_category[i].text;
this.collection_category[form_array_index].category = this.add_category[i].text;
}
}
this.cat_value = true;
}
console.log(this.collection_category);
this.addSubCategory();
this.addQuestion();
}
addSubCategory(){
this._q_service.addSubCategory().
subscribe(
data => {
this.add_subcategory = Array.from(data);
this.subcategory_value = [];
this.options = {
multiple: true
}
let id = 0;
let text = 'Select Sub Category';
this.add_subcategory.unshift({id,text});
this.subcategory_value = [];
this.subcategory_current = this.subcategory_value;
},
err => console.error(err)
);
}
changedSubcategory( data: any, form_array_index: any ) {
this.subcategory_current = data.value;
if(this.subcategory_current.length > 0){
let len = this.add_subcategory.length;
for (let i = 0; i < len; ++i) {
if (this.add_subcategory[i].id == this.subcategory_current) {
this.get_subcategory = this.add_subcategory[i].text;
this.collection_category[form_array_index].subcategory = this.add_subcategory[i].text;
// this.collection_subcategory[form_array_index].subcategory_collection = [];
}
}
this.sub_value = true;
}
}
addQuestion(){
this._q_service.questionList().
subscribe(
data => {
this.add_question = Array.from(data);
this.question_value = [];
let id = 0;
let text = 'Select Question';
this.add_question.unshift({id,text});
this.subcategory_value = ['0'];
this.question_current = this.question_value;
},
err => console.error(err)
);
}
changedQuestion(data: any) {
this.question_current = data.value;
if(this.question_current != 0){
let len = this.add_question.length;
for (let i = 0; i < len; ++i) {
if (this.add_question[i].id == this.question_current) {
this.get_question = this.add_question[i].text;
}
}
}
}
addFormRow(){
let new_form ={
id: '',
segment: '',
category: '',
subcategory: '',
question: ''
};
// this.category_current.push(0);
let segment_categories = {
segment: '',
category: '',
subcategory: '',
question: ''
};
//this.category_current[form_array_index].category
this.collection_category.push(segment_categories);
this.forms.push(new_form);
}
*And every time the user hit the Add Form button it dynamically add form *
But it gives me an error every time I add form the first accordion is not working on the second form but the first form is working well

Why ajax execute only first time

can someone explain me why this execute only first time? It should remove item from minishopping cart, but it works only first time.
This is html section:
<div data-itemid="#item.Id" class="item #(i == 0 ? "first" : null) row">
<div class="remove">
<input class="remove-item-cart-btn" type="button" value="Remove" data-itemid="#item.Id" />
</div>
I have Action in my controler:
[HttpPost]
public ActionResult RemoveProductFromCart_Catalog(int id)
{
var shoppingCartItem = _workContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart && sci.Id == id)
.LimitPerStore(_storeContext.CurrentStore.Id).FirstOrDefault();
_shoppingCartService.DeleteShoppingCartItem(shoppingCartItem, ensureOnlyActiveCheckoutAttributes: true);
//display notification message and update appropriate blocks
var updatetopcartsectionhtml = string.Format(_localizationService.GetResource("ShoppingCart.HeaderQuantity"),
_workContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
.LimitPerStore(_storeContext.CurrentStore.Id)
.ToList()
.GetTotalProducts());
var updateflyoutcartsectionhtml = _shoppingCartSettings.MiniShoppingCartEnabled
? this.RenderPartialViewToString("FlyoutShoppingCart", PrepareMiniShoppingCartModel())
: "";
return Json(new
{
success = true,
message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheCart.Link"), Url.RouteUrl("ShoppingCart")),
updatetopcartsectionhtml = updatetopcartsectionhtml,
updateflyoutcartsectionhtml = updateflyoutcartsectionhtml
});
}
and this is js function:
$(function() {
$(".mini-shopping-cart").on("click", '.remove-item-cart-btn', function (e)
{
alert("test");
var $this = $(this);
$.ajax({
url: '#Url.Action("RemoveProductFromCart_Catalog", "ShoppingCart")',
cache: false,
data:
{
id: $this.data('itemid')
},
success: function (data, textStatus, jqXHR)
{
$("#flyout-cart").replaceWith(data.updateflyoutcartsectionhtml);
jQuery.each($(".cart-qty"), function (i, val) {
$(val).text(data.updatetopcartsectionhtml);
});
}
});
e.preventDefault();
});
});
I am new in js so dont blame me(a lot).
Thanks in advance!
This is the whole html section:
<div id="flyout-cart" class="flyout-cart">
<div class="mini-shopping-cart">
<div class="count">
#if (Model.TotalProducts == 0)
{
#T("ShoppingCart.Mini.NoItems")
}
else
{
#Html.Raw(string.Format(T("ShoppingCart.Mini.ItemsText").Text, string.Format("{1}", Url.RouteUrl("ShoppingCart"), string.Format(T("ShoppingCart.Mini.Items").Text, Model.TotalProducts))))
}
</div>
#if (Model.TotalProducts > 0)
{
<div class="items">
#for (int i = 0; i < Model.Items.Count; i++)
{
var item = Model.Items[i];
<div data-itemid="#item.Id" class="item #(i == 0 ? "first" : null)">
#if (Model.ShowProductImages)
{
<div class="picture">
<a href="#Url.RouteUrl("Product", new { SeName = item.ProductSeName })" title="#item.Picture.Title">
<img alt="#item.Picture.AlternateText" src="#item.Picture.ImageUrl" title="#item.Picture.Title" />
</a>
</div>
}
<div class="product">
<div class="name">
#item.ProductName
</div>
#if (!String.IsNullOrEmpty(item.AttributeInfo))
{
<div class="attributes">
#Html.Raw(item.AttributeInfo)
</div>
}
<div class="price">#T("ShoppingCart.Mini.UnitPrice"): <span>#item.UnitPrice</span></div>
<div class="quantity">#T("ShoppingCart.Mini.Quantity"): <span>#item.Quantity</span></div>
</div>
<div class="remove">
<input class="remove-item-cart-btn" type="button" value="Remove" data-itemid="#item.Id" />
</div>
</div>
}
</div>
<div class="totals">#T("ShoppingCart.Totals.SubTotal"): <strong>#Model.SubTotal</strong></div>
<div class="buttons">
#if (Model.DisplayShoppingCartButton)
{
<input type="button" value="#T("ShoppingCart.Mini.ViewCart")" class="button-1 cart-button" onclick="setLocation('#(Url.RouteUrl("ShoppingCart"))')" />
}
#if (Model.DisplayCheckoutButton)
{
var checkoutUrl = "";
if (Model.AnonymousCheckoutAllowed && Model.CurrentCustomerIsGuest)
{
checkoutUrl = Url.RouteUrl("LoginCheckoutAsGuest", new { returnUrl = Url.RouteUrl("ShoppingCart") });
}
else
{
checkoutUrl = Url.RouteUrl("Checkout");
}
<input type="button" value="#T("Checkout.Button")" class="button-1 checkout-button" onclick="setLocation('#checkoutUrl')" />
}
</div>
}
</div>

Categories