fetch Data into angular2 form - asp.net-mvc

i am trying to fetch users data back into form but i am unable to do so,
please help me,
here is my code.
i want to get the data loaded into the edit form on OnInit(), i am using angular 4 , and backend is .Net MVC,
and also explain what's wrong in my code.
code for list component
enter code here
`<table class="table table-hover">
<thead>
<tr>
<th>Contact ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone </th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let contact of contacts">
<td>{{ contact.ContactID }}</td>
<td>{{ contact.FirstName }}</td>
<td>{{ contact.LastName }}</td>
<td>{{ contact.Phone }}</td>
<td>{{ contact.Email }}</td>
<a [routerLink]="['/contactedit', contact.ContactID]">Edit</a>
<!-- <td><a (click) = "onEdit( contact.ContactID )" class="btn btn-primary" >Edit</a> </td> -->
<td><a (click) = "onDelete( contact.ContactID)" class="btn btn-primary" >Delete</a></td>
</tr>
</tbody>
</table>`
here is the html of edit form component
`<form
[formGroup] = "form"
(ngSubmit) = "onSubmit(form.value)">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="FirstName" placeholder="Enter email" formControlName="FirstName">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="LastName" placeholder="Password" formControlName="LastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="tel" class="form-control" id="Phone" placeholder="Password" formControlName="Phone">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="Email" placeholder="Password" formControlName="Email" >
</div>
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Update</button>
<button type="reset" class="btn btn-default">Clear</button>
</form>`
here is the code of edit form component.ts
`import { Component , OnInit } from '#angular/core';
import { FormBuilder,Validators, FormGroup } from '#angular/forms';
import { Contact } from './contact.interface';
import { ActivatedRoute , Router } from '#angular/router';
import { MediaService } from './media.service';
import 'rxjs/add/operator/switchmap';
#Component({
selector: 'my-media-form',
//moduleId: module.id,
templateUrl: 'app/media-form.component.html'
})
export class MediaFormEditComponent implements OnInit {
id: string;
currentContact: Contact;
contactForm: FormGroup;
private sub: any;
form;
constructor(private router: Router,
private route : ActivatedRoute,
private formBuilder: FormBuilder,
private mediaService: MediaService){}
ngOnInit(){
debugger;
this.form = this.formBuilder.group({
FirstName: this.formBuilder.control('',Validators.required),
LastName: this.formBuilder.control('',Validators.required),
Email: this.formBuilder.control('', Validators.compose([Validators.required])),
Phone: this.formBuilder.control('',Validators.required)
});
this.sub = this.route.params
.map(params => params['id'])
.switchMap(id => this.mediaService.getContactById(id))
.subscribe((cont: Contact) => {
this.currentContact = cont;
this.contactForm.setValue({
FirstName : cont.FirstName,
LastName: cont.LastName,
Email: cont.Email,
Phone: cont.Phone
});
});
}
onSubmit(Data){
this.mediaService.UpdateContact(Data)
.subscribe(data => this.router.navigate(['contacts']));
}
}`

First create an array before your loop (after fetch data):
let newFormArray: FormGroup[] = [];
In your loop:
newFormArray.push(this.fb.group({ FirstName: [cont[i].FirstName, Validators.required], LastName: [cont[i].LastName, Validators.required] //...
}));
Then make your form:
this.form = this.fb.group({
array: this.fb.array(newFormArray)
})
Imports: import { FormControl, FormArray, FormGroup, FormBuilder, Validators } from '#angular/forms';

Related

Why is my anchor tag in Thymeleaf is not redirecting to the local file

I am trying to redirect to another local web page using a tag in Thymeleaf and Spring boot but it is
not working. I am redirecting from index.html to addEdit.html which are in the same folder.
Here is my code.
index.html
<div class="container">
<p th:text="${message}"></p>
<a th:href="#{/addEdit.html}" class="btn btn-outline-info">Add Employee</a> //not working
<table class="table table-bordered table-dark">
<thead class="">
<tr>
<th>#</th>
<th>Name</th>
<th>Departmen</th>
<th>Position</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="employee : ${employees}" >
<th th:text="${employee.id}"></th>
<td th:text="${employee.name}"></td>
<td th:text="${employee.department}"></td>
<td th:text="${employee.position}"></td>
<td>
<form action="delete">
<input type="submit" value="Delete" class="btn btn-outline-warning"/>
</form>
</td>
<td>
<form action="edit">
<input type="submit" value="Edit" class="btn btn-outline-info"/>
</form>
</td>
</tr>
</tbody>
</table>
</div>
my EmployeeController
#Autowired
private employeeRepo repo;
#RequestMapping("/")
public String home(Model model) {
List<Employee> list = new ArrayList<>();
list = repo.findAll();
model.addAttribute("employees",list);
return "index";
}
#PostMapping("/addEmployee")
public void addEmployee(Employee employee,Model model) {
repo.save(employee);
model.addAttribute("message","Add Successfully");
home(model);
}
my addEdit.html
<div class="container bg-light">
<form action="addEmployee">
<input class="form-control form-control-sm" type="text" placeholder="Name" name="name"><br>
<input class="form-control form-control-sm" type="text" placeholder="Department" name="department"><br>
<input class="form-control form-control-sm" type="text" placeholder="Position" name="postion"><br/>
<input type="submit" value="Add Employee" class="btn btn-outline-success btn-lg btn-block">
</form>
</div>
You should not include the .html in your link. The link should point to a URL that your controller exposes. There is currently no controller method that exposes the /addEdit url for example.
So update your controller:
#GetMapping
public String addEmployee(Model model) {
// add model attributes here as needed first
return "addEdit" // This refers to the view, so 'addEdit.html'
}
Now update the link to:
<a th:href="#{/addEdit}" class="btn btn-outline-info">Add Employee</a>

angular7 querystring user enter the id and password getting undefined

```
**Below code working fine as expected but getting Id and Password
'undefind&undefind'.**
**I need to show user enter details.Like ID:test and Password;test123
Could you please help me on this.**
**am getting this format.**
http://localhost:8089/api/Logins/CheckPassword?ID=[undefind]&Password=
[undefind
need this format
http://localhost:8089/api/Logins/CheckPassword?ID=[test]&Password=[test123]
```text
Can anyone help me please?
**login.services**
```
getLoginById(UserID: string,Password: string): Observable<Login[]>{
debugger;
let params=new HttpParams().set('ID', UserID).set('Password',Password);
console.log(params.toString());
return this.http.get<Login[]>(this.baseURL,{params});
}
```
**login.component.ts**
```typescript
constructor(
// private formbuilder: FormBuilder,
private loginService: LoginService,
private router:Router,
private route: ActivatedRoute, private formbuilder: FormBuilder)
{}
onFormSubmit() {
this.loading = false;
const client = this.clientForm.value;
this.getLogin(client);
this.clientForm.reset();
}
ngOnInit() {
debugger;
this.clientForm = this.formbuilder.group({
UserID: ['', [Validators.required]],
Password: ['', [Validators.required]]
});
}
getLogin(login :Login){
debugger;
this.loginService.getLoginById(this.clientForm.UserID,this.clientForm.Passwor
d).subscribe(() => {
this.loading = true;
});
}
```
```text
**login.component.html**
```
<div class="container">
<mat-card>
<mat-toolbar color="accent">
<div align="center" style="color:white;text-align:right;">
Login
</div>
</mat-toolbar>
<br>
<br>
<mat-card-content>
<form [formGroup]="clientForm"
(ngSubmit)="onFormSubmit(clientForm.value)">
<table>
<tr>
<td class="tbl1">
<mat-form-field class="demo-full-width">
<input formControlName="UserID" matTooltip="Enter login UserID"
matInput placeholder="UserID">
</mat-form-field>
<mat-error>
<span *ngIf="!clientForm.get('UserID').value &&
clientForm.get('UserID').touched">
</span>
</mat-error>
</td>
</tr>
<tr>
<td class="tbl1">
<mat-form-field class="demo-full-width">
<input formControlName="Password" matTooltip="Enter login
Password" matInput placeholder="Password">
</mat-form-field>
<mat-error>
<span *ngIf="!clientForm.get('Password').value &&
clientForm.get('Password').touched">
</span>
</mat-error>
</td>
</tr>
</table>
<table>
<tr>
<td class="content-center">
<button type="submit" mat-raised-button color="accent"
matTooltip="Click Submit Button" [disabled] =
"!clientForm.valid">Login</button>
<button type="reset" mat-raised-button color="accent"
matTooltip="Click Reset Button" (click) =
"resetForm()">Reset</button>
</td>
</tr>
</table>
</form>
</mat-card-content>
</mat-card>
</div>
```
As Daniel A. White says, it's not a good idea to pass username and password in url parameters as you ask to do.
You'll open a huge security hole and everyone who can intercept your request can stole you your sensitive data.
Anyway if you wish to do this kind of operation, assuming
http://localhost:8089/api/Logins/CheckPassword?ID=[UserID]&Password=[Password]
refers to an endpoint (web api), you have to use this.http.get() this way:
const params: {
'params': {
'ID': userID,
'Password': password
}
};
this.http.get('http://localhost:8089/api/Logins/CheckPassword', params);

Add text boxes data to grid temporarily using knockout.js

Html code
<label class="control-label">Contact Person</label>
<input class="form-control" type="text" placeholder="Enter Contact name" data-bind="value: ContactPerson" data-validate='{"required":"true"}'><br />
<label class="control-label">ContactNo</label>
<input class="form-control" type="tel" data-bind="value: ContactNo" placeholder="ContactNo" data-validate='{"required":"true"}'><br />
<label class="control-label">E-Mail</label>
<input class="form-control" type="email" data-bind="value: Email" placeholder="Email" data-validate='{"required":"true","email":"true"}'><br />
<table class="table table-hover table-bordered" id="listTable">
<thead>
<tr>
<th>ContactPerson</th>
<th>ContactNo</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody data-bind="template:{name: 'Process-list',
foreach: rootViewModel.BodyContent.ProcessList }">
</tbody>
</table>
when I click on add button the data in the three text box should bind to grid ,
and when i click on delete button of row in grid it should disappear for this i need viewmodel.
Thanks
Here's a quick view model that does the requirements. I selected ContactNo as the primary key since they're supposed to be unique. You can use ids if needed instead. It would also be a good idea to run your validations before add method is called.
var viewModel = function(){
var self = this;
self.ContactPerson = ko.observable();
self.ContactNo = ko.observable();
self.Email = ko.observable();
self.ProcessList = ko.observableArray();
self.add = function(){
self.ProcessList.push({
ContactPerson: self.ContactPerson(),
ContactNo: self.ContactNo(),
Email: self.Email(),
});
self.ContactPerson('');
self.ContactNo('');
self.Email('');
};
self.delete = function(data, event){
self.ProcessList.remove(function(listObject){
return listObject.ContactNo === data.ContactNo;
});
};
};
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label class="control-label">Contact Person</label>
<input class="form-control" type="text" placeholder="Enter Contact name" data-bind="value: ContactPerson" data-validate='{"required":"true"}'><br />
<label class="control-label">ContactNo</label>
<input class="form-control" type="tel" data-bind="value: ContactNo" placeholder="ContactNo" data-validate='{"required":"true"}'><br />
<label class="control-label">E-Mail</label>
<input class="form-control" type="email" data-bind="value: Email" placeholder="Email" data-validate='{"required":"true","email":"true"}'><br />
<button data-bind="click: add">Add Data</button>
<table class="table table-hover table-bordered" id="listTable">
<thead>
<tr>
<th>ContactPerson</th>
<th>ContactNo</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody data-bind="template:{name: 'Process-list',
foreach: ProcessList }">
</tbody>
</tbody>
</table>
<script type="text/html" id="Process-list">
<tr>
<td data-bind="text: ContactPerson"></td>
<td data-bind="text: ContactNo"></td>
<td data-bind="text: Email"></td>
<td><button data-bind="click: $root.delete">Delete</button></td>
</tr>
</script>

HttpPostedFileBase is coming null

below is the code in my View
#using ClaimBuildMVC.Models
#model IEnumerable<Asset>
#{
ViewBag.Title = "AssetsPage";
Layout = "~/Views/Shared/_SuperAdminLayout.cshtml";
}
<script type="text/javascript">
</script>
#using (Html.BeginForm("AssetsPage", "SuperAdmin", FormMethod.Post,new{enctype = "multipart/form-data"}))
{
<div class="Content-inner-pages">
<div class="TopHeading TopHeading2">
<h2>Assets</h2>
<a class="CreateBtn AssetsBtn" href="Javascript:void(0);" onclick="javascript:$('#hdnIsNew').val('1')">Add Asset</a>
<div class="clearfix"></div>
</div>
<input type="hidden" id="hdnIsNew" value="1" />
<input type="hidden" id="hdnRecId" />
<!-- Slide Popup panel -->
<div class="cd-panel from-right AddAssetForm">
<header class="cd-panel-header">
<h3>Add Asset</h3>
Close
</header>
<div class="cd-panel-container">
<div class="cd-panel-content">
<div class="form-horizontal form-details popup-box">
<div class="form-group">
<label class="col-md-5 control-label">
Asset Title
</label>
<div class="col-md-7">
<input type="text" id="txtTitle" name="txtTitle" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Description</label>
<div class="col-md-7">
<textarea id="txtDesc" class="form-control" cols="5" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-5 control-label">Attachment</label>
<div class="col-md-7">
<input type="file" id="file" class="custom-file-input">
</div>
</div>
<div class="form-group">
<div class="col-md-7 col-md-offset-5">
<input type="submit" value="Save" name="actionType" class="btn-class btn-success">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-content Custom-DataTable">
<table id="AdministationAssets" class="table table-hover dt-responsive CustomDatable AdministationAssetsTable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width:5%;">Assets</th>
<th style="width:15%;">
#Html.DisplayNameFor(model =>model.Title)
</th>
<th style="width:50%;">
#Html.DisplayNameFor(model =>model.Description)
</th>
<th style="width:8%;">Options</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td></td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem =>item.Description)
</td>
<td>
#Html.ActionLink("Edit", "AddEditRecord", new{ id = item.ID }, new { #class = "ActionEdit AssetEdit", onclick ="javascript:GetEditDetails(" + item.ID + ");" })
#Html.ActionLink("Delete", "AssetDelete", new{ id = item.ID }, new { #class = "ActionDelete", onclick = "return confirm('Are You Sure delete this record?');", })
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
and below is my controller that what i want to call when click on save button but 'img' is coming as null and after searching in google i found that to add #using(Html.BeginForm()) but still it is coming as null
[HttpPost]
public ActionResult AssetsPage(Asset ast, HttpPostedFileBase file)
{
using (GenericUnitOfWork gc = new GenericUnitOfWork())
{
if (HttpContext.Request.Files.Count > 0)
{
ast.ContainerName = "reports";
ast.BlobName = HttpContext.Request.Files[0].FileName;
ast.BlobUrl = BlobUtilities.CreateBlob(ast.ContainerName, ast.BlobName, null, GetStream(HttpContext.Request.Files[0].FileName));
ast.FileName = HttpContext.Request.Files[0].FileName;
}
gc.GetRepoInstance<Asset>().Add(ast);
gc.SaveChanges();
}
return RedirectToAction("AssetsPage");
}
Not able to find the solution. Please help or give some reference if possible.
Asp.Net MVC default model binding works with name attribute, So add name="file" attribute with input type="file" as shown :-
<input type="file" name="file" id="file" class="custom-file-input">

Cant display values to Textbox's at second time using Jquery

I am developing MVC application.
I have shown the confirm modal box.
It works properly only at once.... If I open it again it didnt work at all...
check below picture....
when I put the entries in the dispatch text box(34), on blur event it multiplies bundle size value(60) and shows in Pisces text box (2040). its working fine,
when I close the box and open it again and put the values again in dispatch text box, its not working at all...
Here is my code...
<h2 style="font-size:22px;">Dispatch </h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Create", "Dispatch", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmCreate" }))
{
#Html.ValidationSummary(true)
<div class="row-fluid">
<div class="span12 roundedDiv" >
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Primary Information</legend>
</div>
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Product List</legend>
<div class="row-fluid">
<table class="table table-striped table-hover" id="mytable">
<thead>
<tr >
<th>
Section Name
</th>
<th>
Section Code
</th>
</tr>
</thead>
<tbody id="tbody">
#foreach (var item in ViewBag.ProductList)
{
<tr id="tableRow" >
<td >
#item.SectionName
</td>
<td >
#item.SectionCode
</td>
<td id="editRow" >
Edit
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="span11" >
<div class="span3"> Order Date : #System.DateTime.Now.ToShortDateString()</div>
<div class="span9" style="text-align:right">
<button type="button" class="btn btn-primary" id="btnDispatch" >Dispatch</button>
<input class="btn btn-default" value="Back" style="width:40px;" onclick="window.location.href='#Url.Action("index") '"/>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('.editClass').click(function () {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose1"> × </button><h5 id="dataConfirmLabel">Edit </h5> </div><div class="modal-body" ><html><table style="width:530px"><tr> <th style="width:120px">Bundle Size</th><th>Count</th><th>Dispatch</th> <th> Pieces</th> </tr><tr> <td><div id="bundleSize1" >60 </div></td> <td><div id="count1">3</div></td> <td><input id="dispatchValue1" type="text" style="width:100px ;height:15px ;margin:1px" /></td> <td> <input id="pieces1" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td><div id="bundleSize2" >10</div></td> <td><div id="count2">8</div></td><td><input id="dispatchValue2" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces2" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr style="border-bottom:solid #e8eef4 thick;"> <td><div id="bundleSize3" >1</div></td><td><div id="count3">20</div></td><td><input id="dispatchValue3" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces3" class="txt" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td colspan="3" style ="text-align: right; border-right:solid white;"> Total</td> <td> <input id="total" type="text" value="0" style="width:100px ;height:15px ;margin:1px" disabled /></td></tr></table> </html></div> <div class="modal-footer"><button type="button" id="btnOk1" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> <button type="button" id="btnCancel1" class="btn btn-default" data-dismiss="modal" aria-hidden="true" >Cancel</button> </div></div> ');
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal').modal({ show: true });
});
$('body').on('click', '#btnOk1', function() {
});
$('body').on('click', '#btnCancel1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
Below is the Blur event of textbox, where calculation take place. calculation is ok...but value dont assigned to Pieces textbox.
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
var bundleSize = $('#bundleSize1').text();
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
var ntotal= $('#total').text();
$('#supplyQuantity').val(sum);
if(ntotal > 0)
{
var ntotal = $('#total').val();
var sum = parseFloat(ntotal) +parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
else
{
var sum = parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
});
});
$(document).ready(function () {
$('#btnDispatch').click(function () {
$('body').append('<div id="dataConfirmModal1" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose"> × </button> <h5 id="dataConfirmLabel">Dispatch Alert</h5> </div><div class="modal-body"><h5>This order is dispatched.</h5><br/></div><div class="modal-footer"><button type="button" id="btnOk" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> </div></div> <div class="modal-backdrop"></div>');
$('#dataConfirmModal1').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal1').modal({ show: true });
});
$('body').on('click', '#btnOk', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
});
</script>
Can you please call alert in this code block;
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
alert(dispatchValue );
var bundleSize = $('#bundleSize1').text();
alert(bundleSize);
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
I think at second time one of that alert values is null or empty. Check that please. You lose the control of that field.

Resources