Саске
Саске

Reputation: 190

Angular 6 with .net core model not binding

So I have been learning some .net core and I am building an API with it. Normally I would work with angular and send requests there.

I have the following angular snippet:

const BloclDTO = {
    Period: value.YearFormControl + value.MonthFormControl + '00',
    ValueBlock1: value.OnelFormControl,
    ValueBlock2: value.TwolFormControl,
    ValueBlock3: value.ThreelFormControl,
    ValueBlock4: value.FourlFormControl,
    ParamId: 1
}

Then there's the backend model for the same data:

public class MiddleDTO
{
    public string Period { get; set; }
    public double ValueBlock1 { get; set; }
    public double ValueBlock2 { get; set; }
    public double ValueBlock3 { get; set; }
    public double ValueBlock4 { get; set; }
    public int ParamId { get; set; }
}

And finally the method that should send it:

in HttpService

addData(param: any) {
    console.log('is http service: ', param);
    return this.HttpClient.post(`api/Data/AddValue`, { params: param });
}

in Component

this.http.addData(BloclDTO).subscribe(res => {
    console.log('res add ', res);
});

in .net Core Controler

[HttpPost]
[Route("AddValue")]
public JsonResult AddValue([FromBody]MiddleDTO param)
{
    if (param == null)
    {
        return Json(new { error = true, text = "param is null" });
    }

    return Json(param);
}

But i have empty data in controller.

Upvotes: 1

Views: 386

Answers (1)

Joe Belladonna
Joe Belladonna

Reputation: 1339

Try this one:

[HttpPost]
[Route("AddValue")]
public IHttpActionResult AddValue([FromBody]MiddleDTO param)
{
    if (param == null)
    {
        return InternalServerError(new Exception("param is null"));
    }

    return OK(param);
}

angular:

addData(param: any) {
        let bodyString = JSON.stringify( param );
        let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
        return this._http.post<any>('api/Data/AddValue', bodyString, { headers: headers });
    }

Upvotes: 1

Related Questions