1

I'm working on ASP.NET core Web API and I do not know how to return something when data inserted into database and then show related toaster on response type as either error or success. I've created an interface where I defined method then created service where I implement interface method and insert data to database then created controller which connect to angular.

Interface method

void AddMurderComplian(Complians complians);

Service method

public void AddMurderComplian(Complians complians)
{
    var complianMurder = new Complians()
    {
        Dead = complians.Dead,
        Wounded = complians.Wounded,
        CriminalsInvolved = complians.CriminalsInvolved,
        CriminalAppearence = complians.CriminalAppearence,
        VehiclesUsed = complians.VehiclesUsed,
        WeaponsDescription = complians.WeaponsDescription,
        SubType = complians.SubType,
        ApplicationUserId = complians.ApplicationUserId
    };
    try
    {

        _appDbContext.Complians.Add(complianMurder);
        _appDbContext.SaveChanges();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Controller

[HttpPost]
[Route("complianMurder")]
public void Post(Complians complian)
{
    _complians.AddMurderComplian(complian);
}

Angular

submitMurderInfo()
{
    this.formModelMurder.SubType = "Murder";
    this.formModelMurder.ApplicationUserId = sessionStorage.getItem("Id");
    this.murderService.murderQuestionnaire(this.formModelMurder).subscribe(
        (res: any)=>{
        if (res.succeeded)
        {
            //   this.toastr.success("Welome ");
            //  this.formModelMurder.Dead = '',
            //  this.formModelMurder.Wounded ='',
            //  this.formModelMurder.CriminalsInvolved = '',
            //  this.formModelMurder.CriminalAppearence = '',
            //  this.formModelMurder.VehiclesUsed = '',
            //  this.formModelMurder.WeaponsDescription ='',
            //  this.formModelMurder.SubType = '',
            //  this.formModelMurder.ApplicationUserId = ''
        }
        else
        {
            // this.toastr.error('Sorry Check your complian');
        }
    });
}
Tanveer Badar
  • 4,541
  • 2
  • 27
  • 31

1 Answers1

1

I would do like this:

public bool AddMurderComplian(Complians complians)
{
  bool succeeded = false;
  var complianMurder = new Complians()
  {
      Dead = complians.Dead,
      Wounded = complians.Wounded, 
      CriminalsInvolved = complians.CriminalsInvolved, 
      CriminalAppearence = complians.CriminalAppearence, 
      VehiclesUsed = complians.VehiclesUsed, 
      WeaponsDescription = complians.WeaponsDescription,
      SubType = complians.SubType,
      ApplicationUserId = complians.ApplicationUserId
  };
  try
  {
      _appDbContext.Complians.Add(complianMurder);
      _appDbContext.SaveChanges();
      succeeded = true;
      return succeeded;
  }
  catch (Exception ex)
  {
      succeeded = false;
      return succeeded;
  }
}

In the controller method:

[HttpPost]
[Route("complianMurder")]
public bool Post(Complians complian)
{
    return _complians.AddMurderComplian(complian);
}

In angular:

submitMurderInfo()
{
  this.formModelMurder.SubType = "Murder";
  this.formModelMurder.ApplicationUserId = sessionStorage.getItem("Id");
  this.murderService
    .murderQuestionnaire(this.formModelMurder)
    .subscribe((res: any) => {
      if (res) {
        // Successfully inserted
      } else {
        // this.toastr.error('Sorry Check your complian');
      }
    });
}
Prashant Pimpale
  • 8,749
  • 6
  • 30
  • 70
  • will try like this and then response to you. – Wasif Zaman Nov 20 '19 at 06:21
  • @parshant what will be the type of method that we defined in interface? should it be bool? – Wasif Zaman Nov 20 '19 at 06:30
  • lots of thanks this show me the result what i was expecting. – Wasif Zaman Nov 20 '19 at 06:46
  • @prahant one more thing . when i inserted similar data to text field mean if i define text field for integer or string it show successfully message but if inserted string into integer then it show 400 bad request on console. how to handle this. – Wasif Zaman Nov 20 '19 at 06:54
  • error: errors: {Wounded: Array(1), CriminalsInvolved: Array(1)} status: 400 title: "One or more validation errors occurred." traceId: "80000009-0002-f800-b63f-84710c7967bb" __proto__: Object headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure response for http://localhost:49601/api/Complians/complianMurder: 400 Bad Request" name: "HttpErrorResponse" ok: false status: 400 statusText: "Bad Request" – Wasif Zaman Nov 20 '19 at 06:56
  • @WasifZaman There must be an exception in the `Post` method while converting that nvarchar into integer value – Prashant Pimpale Nov 20 '19 at 07:00
  • @parshant why not. – Wasif Zaman Nov 20 '19 at 07:03
  • public class Complians { {public int Id { get; set; } public int Dead { get; set; } public int Wounded { get; set; } public int VehiclesUsed { get; set; } public int NoOfPersonsInvolved { get; set; } public string CriminalAppearence { get; set; } public int CriminalsInvolved { get; set; } public int WeaponsUsed { get; set; }public string WeaponsDescription { get; set; } } – Wasif Zaman Nov 20 '19 at 07:09
  • @WasifZaman so for what property your are sending string as a value? – Prashant Pimpale Nov 20 '19 at 09:06
  • i mean that if it handle the success result and show toaster then why it can not show toaster for unsuccessful .i do what you told but it can not handle bad request .. – Wasif Zaman Nov 20 '19 at 12:02
  • @WasifZaman Okay, show `murderQuestionnaire` method or search *handle bad request in http in angular/ observables* or [this](https://stackoverflow.com/questions/46019771/catching-errors-in-angular-httpclient) will help – Prashant Pimpale Nov 20 '19 at 12:12
  • murderQuestionnaire(data: any){ let options=this.CreateBasicHeader(); var murderBody={ Dead: data.Dead, Wounded: data.Wounded, CriminalsInvolved: data.CriminalsInvolved, CriminalAppearence: data.CriminalAppearence, VehiclesUsed: data.VehiclesUsed, WeaponsDescription :data.WeaponsDescription, SubType :data.SubType, ApplicationUserId :data.ApplicationUserId }; return this.http.post(this.BaseUrl + '/Complians/complianMurder' ,JSON.stringify(murderBody),options); } – Wasif Zaman Nov 20 '19 at 16:17
  • i commented my murderquestionnaire service . – Wasif Zaman Nov 20 '19 at 16:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202766/discussion-between-wasif-zaman-and-prashant-pimpale). – Wasif Zaman Nov 21 '19 at 03:00
  • `methodPost() { return this.http.put(url, null, { headers: this.getHeader.HTTPHeader() }) .toPromise() .catch(this.handleError); } private handleError(error: any): Promise { return Promise.reject(error.message || error); }` – Prashant Pimpale Nov 21 '19 at 11:03