Title value was duplicated after a search - javascript

I have a table with data, and I have two inputs (start date and end date) to filter the records.
I can show you a little visual in image below
enter image description here
I enter for example the date 06/02/2019 to 06/02/2020
enter image description here
I press search
(...)
In fact, the title value has been duplicated?
enter image description here
I have two methods:
getPrices() which displays the data in the HTML table
getDetails() which displays the title
HTML.component
<div class="container">
<div class="breadcrumb d-flex justify-content-between border-bottom pb-3">
<h2> Course history {{infoTitle}}</h2>
<button type="button" (click)="goBack()" class="btn btn-primary m-1 btnColor">Back</button>
</div>
<div class="pt-3 container">
<div class="card">
<div class="card-body">
<form #formulaire="ngForm" (ngSubmit)="formulaire.form.valid && getPrices()">
<div class="row mb-4 align-items-end">
<div class="col-12 col-sm-6 col-md-4">
<div class="mb-2">
<h5>Start date </h5>
<input id="previous" name="previous" type="text" class="form-control form-max-width" [(ngModel)]="model.previous" bsDatepicker #previousModel="ngModel" required [maxDate]="(model.today)" (ngModelChange)="model.verifyToday()">
</div>
</div>
<div class="col-12 col-sm-6 col-md-4">
<div class="mb-2">
<h5>End date </h5>
<input id="today" name="today" type="text" class="form-control form-max-width" [(ngModel)]="model.today" bsDatepicker #todayModel="ngModel" [minDate]="(model.previous)">
</div>
</div>
<div class="col-12 col-md-4">
<div class="mb-2">
<button type="submit" class="btn btn-primary" [disabled]="formulaire.form.invalid">
Search
</button>
</div>
</div>
</div>
</form>
typeScript.component
export class HistoricalPricesComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
infoTitle: string = "";
lines: HistoryPoint[] = [];
model: Currency = new Currency();
svm: string;
constructor(
private location: Location,
private service: HistoricalPricesService,
private activatedRoute: ActivatedRoute
) { }
ngOnInit(): void {
let svm: string | null;
svm = this.activatedRoute.snapshot.paramMap.get('svm');
if (!svm) {
this.goBack();
return;
}
this.svm = svm;
this.getPrices();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
getPrices(): void {
this.service.getInstrumentHistoryEquities(this.svm,this.model).pipe(
takeUntil(this.unsubscribe$)
).subscribe(res => {
if (res.HISTO.POINT.length > 0) {
this.lines = res.HISTO.POINT.reverse();
}
this.getDetails(this.svm);
});
}
private getDetails(svm: string): void {
this.service.getInstrumentInfo(svm).pipe(
takeUntil(this.unsubscribe$)
).subscribe(res => {
this.infoTitle += " " + res.ADVTITRE.BASIQUETITRE.LABEL + " (" + res.ADVTITRE.BASIQUETITRE.PLACELABEL + ")";
});
}
goBack(): void {
this.location.back();
}
}

Related

Binding multiple objects to a List<t>

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.

Pass input text value to function per click

I want to insert the value inserted into an input in the database using Angular as the frontend and php as the backend but I'm not able to insert the input value into the method along with the user.id.
The input is for the reason of moderation when clicking on disapprove it is necessary to pass the reason but it is not entering.
import { Component, OnInit, TemplateRef } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { observerMixin } from '#rodrigowba/observer-component';
import { ResponseData, DefaultResponse } from '#rodrigowba/http-common';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { ActionPayload } from '~/ngrx';
import {
HotsiteUser,
HotsiteUsersFacade,
HotsiteUsersFormService,
RegistrationStatusTypes,
UpdateHotsiteUserRequest,
HotsitePointsPrebase,
} from '~/admin/users';
import {
updateHotsiteUser,
hotsiteUserUpdated,
hotsiteUserUpdateFailed,
hotsiteUserRegistrationModerated,
hotsiteUserModerateRegistrationFailed
} from '~/admin/users/state';
import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
#Component({
templateUrl: './view.component.html',
})
export class ViewComponent extends observerMixin() implements OnInit {
user$: Observable<HotsiteUser>;
pointsPrebase$: Observable<HotsitePointsPrebase[]>;
customFields$: Observable<{
field: string,
value: string
}[]>;
registrationStatusTypes = RegistrationStatusTypes;
form: FormGroup;
modalRef: BsModalRef;
submiting = false;
constructor(
private hotsiteUsersFacade: HotsiteUsersFacade,
private hotsiteUsersFormService: HotsiteUsersFormService,
private modalService: BsModalService,
private toastr: ToastrService
) {
super();
this.form = this.hotsiteUsersFormService.updateForm();
}
ngOnInit() {
this.user$ = this.hotsiteUsersFacade.selectCurrentHotsiteUser();
this.customFields$ = this.user$.pipe(
map(user => Object.values(user.custom_fields)),
map(customFields => customFields.map(customField => {
let value = customField.value;
if (Array.isArray(value)) {
value = value.join(', ');
}
return {
field: customField.field,
value
};
}))
);
this.pointsPrebase$ = this.user$.pipe(
map(user => user.id),
distinctUntilChanged(),
tap(id => {
this.hotsiteUsersFacade.fetchHotsitePointsPrebase(id);
}),
switchMap(id => this.hotsiteUsersFacade.selectHotsitePointsPrebaseByHotsiteUser(id))
);
this.observe(this.user$).subscribe(user => {
this.form.patchValue(user);
});
this.observe(
this.hotsiteUsersFacade.ofType(updateHotsiteUser)
).subscribe(() => {
this.submiting = true;
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<ResponseData<HotsiteUser>>>(
hotsiteUserUpdated,
hotsiteUserRegistrationModerated
)
).subscribe(action => {
const { message, data } = action.payload;
this.submiting = false;
this.toastr.success(message);
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<DefaultResponse>>(
hotsiteUserUpdateFailed,
hotsiteUserModerateRegistrationFailed
)
).subscribe(action => {
const { message } = action.payload;
this.submiting = false;
this.toastr.error(message);
});
}
onSubmit(id: string, data: UpdateHotsiteUserRequest) {
this.hotsiteUsersFacade.updateHotsiteUser(id, data);
}
openModal(template: TemplateRef<any>, size = 'modal-md') {
this.modalRef = this.modalService.show(template, { class: size });
}
approveRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: true,reason });
}
rejectRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: false,reason });
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<div class="row mb-3">
<div class="col-12">
<div class="form-group">
<label>Name</label>
<input type="text" [value]="user.name" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>E-mail</label>
<input type="text" [value]="user.email" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>Document</label>
<input type="text" [value]="user.document" class="form-control" readonly />
</div>
</div>
<div class="col-12" *ngFor="let customField of customFields$ | async">
<div class="form-group">
<label>{{ customField.field }}</label>
<input type="text" [value]="customField.value" class="form-control" readonly />
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="admin" color="primary" ></mat-slide-toggle>
<label class="ml-2">Admin</label>
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="active" color="primary" ></mat-slide-toggle>
<label class="ml-2">Active</label>
</div>
</div>
</div>
<ng-container *ngIf="pointsPrebase$ | async as pointsPrebase">
<div class="row mb-3" *ngIf="pointsPrebase.length > 0">
<div class="col-12">
<h4 class="font-16 font-weight-bold">Points</h4>
</div>
<div class="col-12 col-lg-6">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Chave</th>
<th class="text-center">Points</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let points of pointsPrebase">
<td>{{ points.value }}</td>
<td class="text-center">{{ points.points }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</ng-container>
<div class="form-row">
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">
<div class="col-auto">
<label>Reason</label>
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-success"
(click)="approveRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Approved </app-loading-label>
</button>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-danger"
(click)="rejectRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Repproved </app-loading-label>
</button>
</div>
</ng-container>
<div class="col text-right">
<button
type="submit"
class="btn btn-orange"
[disabled]="form.invalid || submiting"
>
<app-loading-label [loading]="submiting">Salvar</app-loading-label>
</button>
</div>
</div>
</form>
Error:
Property 'reason' does not exist on type 'formGroup'
As user776686 suggested, there is a formControlName missing linked to "reason" field.
To get the field value in HTML you should access to the FormGroup controls:
(click)="approveRegistration(user.id, form.controls.reason.value)"
Also you can create a "get" property in TS code and then access to it in HTML:
get reason() {
return this.form.controls.reason.value;
}
(click)="approveRegistration(user.id, reason)"
BTW, a field can be accessed too through the "get" method of a FormGroup:
get reason() {
return this.form.get('reason').value;
}
It expects a control with the attribute formControlName="reason" which is not present here:
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
This might be a reason.
If that doesn't help, you my also want to look into the *ngIf condition here:
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">

Angular 8 - Upload multiple array of images using form builder

I have a product form with different fields like product name, description etc.. also array of images.
Product Form
product name product description
product purity product commodity
Images (Add)
checkbox 1 Image 1
checkbox 2 Image 2
checkbox 3 Image 3.
....
I can able to save in my database product name and product description and other fields but don't how to upload those images. Because images are created on clicking the add button and it may have one or as many images based on requirement.I have created the form using Form builder. Given my code below.
Template :
<form class="kt-form kt-form--group-seperator-dashed" [formGroup]="mmgForm">
<div class="kt-form__section kt-form__section--first">
<div class="kt-form__group">
<div class="row">
<label class="col-lg-2 col-form-label">Product Name:</label>
<div class="col-lg-4">
<mat-form-field class="example-full-width">
<input formControlName="prod_name" matInput placeholder="Enter product name" [ngClass]="{ 'is-invalid': submitted && mmgForm.controls['prod_name'].errors }">
<div *ngIf="submitted && mmgForm.controls['prod_name'].errors" class="invalid-feedback cls-formErr">
<div *ngIf="mmgForm.controls['prod_name'].errors.required">Product name is required</div>
</div>
</mat-form-field>
</div>
<label class="col-lg-2 col-form-label">Product description:</label>
<div class="col-lg-4">
<mat-form-field class="example-full-width">
<textarea formControlName="prod_description" matInput placeholder="Enter product description" rows="5" [ngClass]="{ 'is-invalid': submitted && mmgForm.controls['prod_description'].errors }"></textarea>
<div *ngIf="submitted && mmgForm.controls['prod_description'].errors" class="invalid-feedback cls-formErr">
<div *ngIf="mmgForm.controls['prod_description'].errors.required">Product description is required</div>
</div>
</mat-form-field>
</div>
</div>
</div>
<div class="product_images">
<div class="imageHeading">
<p>
Images (<button mat-icon-button color="primary" matTooltip="Add product" (click) = addImage()><mat-icon>add_circle</mat-icon></button>)
</p>
</div>
<div class="kt-form__group">
<div class="row">
<div class="col-lg-1 imageLabel">#</div>
<div class="col-lg-2 imageLabel">Main Image</div>
<div class="col-lg-3 imageLabel">Choose Image</div>
<div class="col-lg-2 imageLabel">Image</div>
<div class="col-lg-2 imageLabel">Actions</div>
</div>
</div>
<div class="imagesContainer">
<div class="kt-form__group image-container container-1" *ngFor="let image of images; index as i">
<div class="row">
<div class="col-lg-1">{{ i+1 }}</div>
<div class="col-lg-2"><input type="checkbox" /></div>
<div class="col-lg-3"><input type="file" accept="image/*" (change)="imagePreview($event, image)" /></div>
<div class="col-lg-2"><img [src]="image.url.imgUrl" class="prod_image" /></div>
<div class="col-lg-2">
<button mat-icon-button color="warn" matTooltip="Delete Product" type="button" (click)="deleteImage(i)">
<mat-icon>delete</mat-icon>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
Ts File :
// Angular
import { Component, OnInit, ElementRef, ViewChild, ChangeDetectionStrategy, OnDestroy, ChangeDetectorRef } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
// Material
import { SelectionModel } from '#angular/cdk/collections';
import { MatPaginator, MatSort, MatSnackBar, MatDialog, MatRadioButton } from '#angular/material';
import { ProductManagementService } from '../../../../../core/e-commerce/_services/product-management.service';
import { ToastrService } from 'ngx-toastr';
#Component({
selector: 'kt-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.scss'],
})
export class ProductEditComponent implements OnInit {
mmgForm : any;
fileData: File = null;
previewUrl : any = "/assets/media/images/noimage.jpg";
images : any = [];
constructor(
private products: ProductManagementService,
private router: Router,
private route: ActivatedRoute,
private toastr: ToastrService,
private cdr: ChangeDetectorRef,
private FB: FormBuilder,
) {
}
ngOnInit() {
this.createForm();
this.addImage();
}
createForm() {
this.mmgForm = this.FB.group({
prod_name: ['', Validators.required],
prod_description: ['', Validators.required]
});
}
/**
* Form Submit
*/
submit() {
if (this.mmgForm.invalid) {
console.log(this.mmgForm);
return;
}
const controls = this.mmgForm.controls;
var form_values = {
prod_name: controls.prod_name.value,
prod_description: controls.prod_description.value,
}
this.products
.createProduct(JSON.stringify(form_values)).subscribe( //Calling Service
(data) => {
console.log(data);
},
error => {
}
);
}
imagePreview(fileInput: any, image) {
this.fileData = <File>fileInput.target.files[0];
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
image.url.imgUrl = reader.result;
this.cdr.markForCheck();
}
}
addImage(){
let url = {imgUrl : this.previewUrl}
this.images.push({url});
}
deleteImage(index: number) {
this.images.splice(index, 1)
}
}
I would suggest to create a FileUploadService for that.
The Service method:
uploadFiles(Array<File> files): Observable<FileUploadResponse> {
const url = `your-upload-url`;
const formData: FormData = new FormData();
for(File file in files) {
formData.append('file', file, file.name);
}
return this.http.post<FileUploadResponse>(url, formData /*{headers if necessary}*/);
}
Your component.ts:
//[..]
Array<File> files = [];
onFileInputEvent(event: any) {
for(let i = 0; i < event.srcElement.files.length; i++) {
this.fileName = event.srcElement.files[0].name;
this.files.push(event.srcElement.files[0]);
}
}
uploadFiles(){
this.fileUploadService.uploadFile(this.file).subscribe(res => { // do something}, err =>{});
}
Your component.html:
<!-- [..] -->
<input id="fileInput" placeholder="Images" type="file" (change)="onFileInputEvent($event)" accept=".jpg">
Edit with a more beautiful input
<div class="file-input">
<input id="fileInput" placeholder="CSV-Datei" type="file" class="hidden" (change)="onFileInputEvent($event)" accept=".csv">
<label for="fileInput" class="mat-raised-button">Add images</label>
<mat-chip-list *ngIf="fileName">
<mat-chip [removable]="true" (removed)="remove()">
{{fileName}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>

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

How to set Checkbox FormControl for Multiple array control

I am trying toggle/check according specific permissions with array set id's - to set permissions for users according to their user role. for an example an admin would have permissions to create users, delete, and update. My struggle with the code i've posted below is that it toggles all permissions instead of ones passed into formControl im not sure if im doing right.
public userList: Array < User > ;
public principalList: Array < Principal > ;
public permissionList: Array < PermissionItem > ;
public groupPermissionList: Array < PermissionGroup > ;
public permIdArr: Array < number > = [];
public permGrpIdArr: Array < number > = [];
public isSelected = false;
public updatePermsList(ev, id: number) {
console.log(ev.target.checked, id);
if (ev.target.checked) {
this.permIdArr.push(id);
console.log(this.permIdArr);
} else {
this.permIdArr = this.permIdArr.filter(pId => {
return pId !== id;
});
}
}
public updateGrpPermsList(event, id: number) {
if (id === 1) {
let grpid;
this.groupPermissionList.map(i => {
const per = i.permissions;
per.forEach(e => {
grpid = e.id;
this.permGrpIdArr.push(grpid);
});
});
} else if (id === 2) {
console.log('2nd');
} else {
console.log('3rd');
}
this.createNewUserForm.controls['app_user_permissions'].setValue(this.permGrpIdArr);
}
<div class="user-new-container p24">
<div [class.updating]="submitting">
<form [formGroup]="createNewUserForm" (ngSubmit)="onSubmit(createNewUserForm.value)" class="updater">
<div class="row">
<div class="col-lg-6">
<div *ngIf="groupPermissionList" class="row perms">
<div class="col-lg-12">
<h3 class="mb24">Group Permissions</h3>
<div class="row">
<div *ngFor="let p of groupPermissionList;let i = index" class="col-lg-4">
<div class="form-group row">
<div class="col-lg-6 col-sm-10 col-xs-10 toggle-switch">
<input (click)="updateGrpPermsList($event, p.id)" value="p.id" type="checkbox" id="permGrp_{{i}}">
<label for="permGrp_{{i}}">{{p.name}}</label>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
<div *ngIf="permissionList" class="row perms">
<div class="col-lg-12">
<h3 class="mb24">Permissions</h3>
<div class="row">
<div *ngFor="let p of permissionList;let idx = index" class="col-lg-4">
<div class="form-group row">
<div class="col-lg-6 col-sm-10 col-xs-10 toggle-switch">
<input (change)="updatePermsList($event, p.id)" formControlName="app_user_permissions" type="checkbox" [checked]="val" id="perm_{{idx}}">
<label for="perm_{{idx}}">{{p.name}}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>

Categories