I am trying to create a CRUD Application using .Net Core Api with Angular11.I follow this link https://www.codaffection.com/asp-net-core-article/angular-crud-with-asp-net-core-web-api/ for creating this.and I not totally completed all functionality yet.just i created functionality 'Add from information into the database.'But when I click the "Submit" button to add my form data into the database, then I have seen an unexpected situation.also, data could not add to my DB.
Here is my code:-
Backend
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using PaymentApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PaymentApi
{
public class Startup
{
//other code
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "PaymentApi", Version = "v1" });
});
services.AddDbContext<PaymentDetailContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(options=>options.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
);
//other code
}
}
}
Controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PaymentApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PaymentApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{
private readonly PaymentDetailContext _context;
public PaymentDetailController(PaymentDetailContext context)
{
_context = context;
}
// GET: api/PaymentDetail
[HttpGet]
public async Task<ActionResult<IEnumerable<PaymentDetails>>> GetPaymentDetails()
{
return await _context.PaymentDetails.ToListAsync();
}
// GET: api/PaymentDetail/5
[HttpGet("{id}")]
public async Task<ActionResult<PaymentDetails>> GetPaymentDetail(int id)
{
var paymentDetail = await _context.PaymentDetails.FindAsync(id);
if (paymentDetail == null)
{
return NotFound();
}
return paymentDetail;
}
// PUT: api/PaymentDetail/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutPaymentDetail(int id, PaymentDetails paymentDetail)
{
if (id != paymentDetail.PaymentDetailId)
{
return BadRequest();
}
_context.Entry(paymentDetail).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PaymentDetailExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/PaymentDetail
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<PaymentDetails>> PostPaymentDetail(PaymentDetails paymentDetail)
{
_context.PaymentDetails.Add(paymentDetail);
await _context.SaveChangesAsync();
return CreatedAtAction("GetPaymentDetail", new { id = paymentDetail.PaymentDetailId }, paymentDetail);
}
// DELETE: api/PaymentDetail/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeletePaymentDetail(int id)
{
var paymentDetail = await _context.PaymentDetails.FindAsync(id);
if (paymentDetail == null)
{
return NotFound();
}
_context.PaymentDetails.Remove(paymentDetail);
await _context.SaveChangesAsync();
return NoContent();
}
private bool PaymentDetailExists(int id)
{
return _context.PaymentDetails.Any(e => e.PaymentDetailId == id);
}
}
}
Frontend
Payment-Details.model.ts
export class PaymentDetails {
paymentDetailId: number=0;
cardOwnerName: string='';
cardNumber: string='';
expirationDate: string='';
securityCode: string='';
}
PaymentDetails.service.ts
import { Injectable } from '@angular/core';
import { PaymentDetails } from './payment-details.model';
import { HttpClient } from "@angular/common/http"
@Injectable({
providedIn: 'root'
})
export class PaymentDetailsService {
constructor(private http: HttpClient) { }
readonly baseURL = 'http://localhost:55235/api/PaymentDetail'
formData: PaymentDetails = new PaymentDetails();
list: PaymentDetails[];
postPaymentDetail() {
return this.http.post(this.baseURL, this.formData);
}
putPaymentDetail() {
return this.http.put(`${this.baseURL}/${this.formData.paymentDetailId}`, this.formData);
}
deletePaymentDetail(id: number) {
return this.http.delete(`${this.baseURL}/${id}`);
}
refreshList() {
this.http.get(this.baseURL)
.toPromise()
.then(res =>this.list = res as PaymentDetails[]);
}
}
payment-details-form.component.ts
import { Component, OnInit } from '@angular/core';
import{PaymentDetailsService}from 'src/app/shared/payment-details.service'
import { NgForm } from '@angular/forms';
import { PaymentDetails } from 'src/app/shared/payment-details.model';
@Component({
selector: 'app-payment-details-form',
templateUrl: './payment-details-form.component.html',
styleUrls: ['./payment-details-form.component.css']
})
export class PaymentDetailsFormComponent implements OnInit {
constructor(public service:PaymentDetailsService) { }
ngOnInit(): void {
}
onSubmit(form:NgForm)
{
this.service.postPaymentDetail().subscribe(
res=>{
},
err=>{
console.log(err);
}
);
}
}
payment-details-form.component.html
<form novalidate #form="ngForm" (submit)="onSubmit(form)">
<input type="hidden" name="paymentDetailId"
[value]="service.formData.paymentDetailId" />
<div class="from-group">
<label >CARD OWNER NAME</label>
<input class="form-control from-control-lg" placeholder="FULL NAME"
name="cardOwnerName" #cardOwnerName="ngModel" [(ngModel)]="service.formData.cardOwnerName"
required [class.invalid]="cardOwnerName.invalid && cardOwnerName.touched"/>
</div>
<div class="from-group">
<label >CARD NUMBER</label>
<input class="form-control from-control-lg" placeholder="16 DIGIT CARD NUMBER"
name="cardNumber" #cardNumber="ngModel" [(ngModel)]="service.formData.cardNumber"
required maxlength="8" minlength="2" [class.invalid]="cardNumber.invalid && cardNumber.touched"/>
</div>
<div class="row">
<div class="from-group col-md-6">
<label >SECURITY CODE</label>
<input type="password" class="form-control from-control-lg" placeholder="SECURITY CODE"
name="securityCode" #securityCode="ngModel" [(ngModel)]="service.formData.securityCode"
required maxlength="8" minlength="2" [class.invalid]="securityCode.invalid && securityCode.touched"/>
</div>
<div class="from-group col-md-6">
<label >VALID THROUGH</label>
<input class="form-control from-control-lg" placeholder="MM/YY"
name="expirationDate" #expirationDate="ngModel" [(ngModel)]="service.formData.expirationDate"
required [class.invalid]="expirationDate.invalid && expirationDate.touched"/>
</div>
</div>
<br/>
<div class="form-group">
<button class="btn btn-primary" style="display: block;" type="submit" [disabled]=form.invalid >SUBMIT</button>
</div>
</form>
When I run my angular project to add my form data into my DB then I found this error.
when I click submit button to add my data to the database. then I found these errors.I am an absolute beginner. please help.
this is I found visual studio output.
Starting IIS Express ...
Successfully registered URL "http://localhost:55235/" for site "PaymentApi" application "/"
Registration completed for site "PaymentApi"
IIS Express is running.
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Users\Hp\Desktop\fullstack\PaymentApi\PaymentApi
Security Warning: The negotiated TLS 1.0 is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (1,549ms) [Parameters=[@p0='?' (Size = 16), @p1='?' (Size = 100), @p2='?' (Size = 5), @p3='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [PaymentDetails] ([CardNumber], [CardOwnerName], [ExpirationDate], [SecurityCode])
VALUES (@p0, @p1, @p2, @p3);
SELECT [PaymentDetailId]
FROM [PaymentDetails]
WHERE @@ROWCOUNT = 1 AND [PaymentDetailId] = scope_identity();
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'PaymentApi.Models.PaymentDetailContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__169_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:123b0a93-424e-4068-a878-2db210cfdc91
Error Number:8152,State:13,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__169_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:123b0a93-424e-4068-a878-2db210cfdc91
Error Number:8152,State:13,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__169_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:123b0a93-424e-4068-a878-2db210cfdc91
Error Number:8152,State:13,Class:16
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at PaymentApi.Controllers.PaymentDetailController.PostPaymentDetail(PaymentDetails paymentDetail) in C:\Users\Hp\Desktop\fullstack\PaymentApi\PaymentApi\Controllers\PaymentDetailController.cs:line 81
at lambda_method6(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Look at the exception message: "String or binary data would be truncated."
. That means that you're trying to store a string that's larger than the database field's width. Look at the widths of the database fields and see which one is shorter than the string you're entering.
User contributions licensed under CC BY-SA 3.0