0

On the HTML, when you click the exportok() button below, I wish to send the current year (aka.2020) from the selected dropdown to the.NET MVC Controller function called EXPORT via a HTTPGET call "/api/stations/export”.

Admin.component.ts

exportyears = [
    {name: '1 July 2019 to 30 June 2020', id: '2019-2020'},
    {name: '1 July 2020 to 30 June 2021', id: '2020-2021'},
  ];

Admin.component.html

<form>
  <select formControlName="exportyear" [(ngModel)]="reportyear"(change)="onClickMe()">
    <option 
      *ngFor="let exportyear of exportyears" [ngValue]="exportyears"
    >
      {{ exportyear.id }}
    </option>
  </select>
</form>

<button class="btn btn-primary" type="button" (click)="exportOk(exportyears[0].id)">
<i class="glyphicon glyphicon-ok"></i>&nbsp;OK</button>

Service.ts

export(reportyear: string): Observable<Response> {
  
//  let headers = new Headers();
  //   headers.append('Content-Type', 'application/json');
 // headers.append('reportyear', reportyear);

  let request = new Request({
    method: RequestMethod.Get,
    url: environment.baseUrl + "/api/stations/export",
    responseType: ResponseContentType.Blob,
    body: {reportyear}
  }
);

Station.ts

exportOk(reportyear: string) {
  this.exporting = true;
  this.exportMessage = null;

  this.stationsService.export(reportyear)
    .subscribe(
      (res: Response) => {
        this.exporting = false;
        this.exportModal.hide();
        Utils.launchAttachment(res);
      },
      error => {
        this.exporting = false;
        if (error.error) {
          this.exportMessage = error.error;
        }
        else {
          this.exportMessage = error;
        }
      }
    );

ASP.NET MVC Controller Controller.cs

[HttpGet("export")]
  public async Task<IActionResult> Export([FromBody]string reportyear)
  {
    var obj = reportyear; //show me the year so I can use it further down the line…..
    var stations = await stationRepository.GetExportAsync();
    ......
  }
Michael
  • 19
  • 6
  • Do you have any error like 500 or 400 ? If not then it must be between what you send (url/data) and the controller action. You should have something like this at the end: "/api/stations/export/2019-2020” right ? Try this [HttpGet("year")] public async Task Export(string year) { ... } – Sinan Aug 19 '20 at 08:56
  • What is in the HttpGet parenthesis must be the same as the one in the function parameters. Try with curly brackets: [HttpGet("{year}")]. – Sinan Aug 19 '20 at 09:00
  • Thanks Sinan. The error i get is :5000/api/stations/export:1 Failed to load resource: the server responded with a status of 415 (Unsupported Media Type). will try [HttpGet("export {year}")]. Which i think is because its not recognising the header. – Michael Aug 19 '20 at 09:19
  • OK now i updated to [HttpGet("export{reportyear}")] and I get a 404 Not Found. – Michael Aug 19 '20 at 09:39
  • in your url -> https://localhost:5000/api/stations/export, stations is your controller name and export is the action. So your function name must be Export, until here every is ok. It not [HttpGet("export {year}")] but [HttpGet("{year}")]. – Sinan Aug 19 '20 at 09:41

1 Answers1

0

I have something like this, it may help you.

        /// <summary>
    /// Find a product by name
    /// </summary>
    /// <param name="Name"></param>
    /// <returns></returns>
    [HttpGet("{name}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetByName(string name)
    {
        try
        {
            var item = await _productService.GetOneByName(name);

            if (item != null)
            {
                return Ok(item);
            }
            return NotFound();
        }
        catch (System.Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, ex.Message.ToJson());
        }
    }    

you can see that what is in the curly brackets [HttpGet("{name}")] matches what is in the function parameters GetByName(string name). Btw, I suggest you to use postman for debugging your api if you don't.

UPDATE
try this:

export(reportyear: string): Observable<Response> {

let request = new Request(
   {
      method: RequestMethod.Get,
      url: environment.baseUrl + "/api/stations/export" + "/" + reportyear,
      responseType: ResponseContentType.Blob
   }
);
Sinan
  • 898
  • 1
  • 9
  • 23
  • Thanks Sian. I get what your saying now. Ive updated the MVC controller to [HttpGet("{reportyear}")] public async Task Export(string reportyear) but im still getting a 404. will check out Postman too – Michael Aug 19 '20 at 10:05
  • Ok, so it means that there is nothing that matches your request from the database. – Sinan Aug 19 '20 at 10:06
  • Not yet, i still get a 404. The Angular function is (click)="exportOk(exportyears[0].id). But i can see what you mean, it needed the {reportyear} – Michael Aug 19 '20 at 10:08
  • exactly ! your are close enough. – Sinan Aug 19 '20 at 10:09
  • i think i need to rework this export(reportyear: string): Observable { let headers = new Headers(); headers.append('reportyear', reportyear); let request = new Request({ method: RequestMethod.Get, url: environment.baseUrl + "/api/stations/export", responseType: ResponseContentType.Blob } ); – Michael Aug 19 '20 at 10:12
  • Are you trying to insert data to your database with "export" ? If so then you need to use httppost. I found a kind of related answer that I posted here: https://stackoverflow.com/questions/47908637/display-json-array-angular-5-httpclient/47917853#47917853 – Sinan Aug 19 '20 at 10:23
  • Thanks Sinan. Im not inserting any data, when you click the export button, i wish to send in the year parameter) so I can start an excel import. When i changed the MVC view to [httpGet("export")] it recognises my controller and hits the function breakpoint, however the public async Task Export(string reportyear) is not recognising the report year. Is this because Angular code above (export(reportyear: string): Observable {} isnt working? – Michael Aug 20 '20 at 02:52
  • so something like this? export(reportyear: string): Observable { let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('reportyear', reportyear); let request = new Request({ method: RequestMethod.Get, url: environment.baseUrl + "/api/stations/export", responseType: ResponseContentType.Blob, {headers: headers}) } ); – Michael Aug 20 '20 at 03:10
  • Ive edited the original JSON with the body response but it's still not working. Any suggestions please? I can see the year value isn't null in the function but the MVC Controller cannot see the year value (although the MVC controller hits the breakpoint in the function now). – Michael Aug 20 '20 at 04:13
  • Sup Michael :) If you update your code then you should edit your main question with a section named UPDATE in bold and paste your code with some new information. – Sinan Aug 20 '20 at 04:19
  • Btw if your request type is a GET then you can't have a body. So remove that one. Here a link about REQUEST: https://developer.mozilla.org/en-US/docs/Web/API/Request/Request – Sinan Aug 20 '20 at 04:38
  • If you have multiple data to send with the get request then you will have something like this: http://localhost:5000/api/stations/export?quesrystring where querystring look like this: field1=value1&field2=value2&field3=value3 – Sinan Aug 20 '20 at 04:47
  • I changed the Service.ts try that. – Sinan Aug 20 '20 at 04:51
  • Thanks Sinan for your help. Both your suggestions helped me get this to work. I needed to update my MVC view as follows: [HttpGet("export/{reportyear}")] and needed to add the Angular parameter like you suggested: url: environment.baseUrl + "/api/stations/export" + "/" + reportyear and now the end result is a string value in my MVC controller that matches my dropdown selection from the Angular application. Thankyou :) I can't believe i missed that. – Michael Aug 20 '20 at 05:11