Passed parameter in ASP.NET Core 5 reactjs textfield to controller is always 0

155 Views Asked by At

I am new to React.js and ASP.NET Core 5 and I'm developing using Visual Studio Mac. I'm having this problem where the value being passed from text field to controller is always zero (0) even though I input different numbers. I'm trying to get the value of absentDays and workedDays but it always return 0 in the controller. Here's my code snippet:

Calculate.js

{ this.state.typeId === 1? 
<div className='form-group col-md-6'>
  <label htmlFor='inputAbsentDays4'>Absent Days: </label>
  <input type='text' className='form-control' id='inputAbsentDays4' onChange={this.handleChange.bind(this)} value={this.state.absentDays} name="absentDays" placeholder='Absent Days' />
</div> :
<div className='form-group col-md-6'>
  <label htmlFor='inputWorkDays4'>Worked Days: </label>
  <input type='text' className='form-control' id='inputWorkDays4' onChange={this.handleChange.bind(this)} value={this.state.workedDays} name="workedDays" placeholder='Worked Days' />
</div>
}
</div>

async calculateSalary() {
    this.setState({ loadingCalculate: true });
    const token = await authService.getAccessToken();
    const requestOptions = {
        method: 'POST',
        headers: !token ? {} : { 'Authorization': `Bearer ${token}`,'Content-Type': 'application/json' },
        body: JSON.stringify({id: this.state.id,absentDays: this.state.absentDays,workedDays: this.state.workedDays})
    };
    const response = await fetch('api/employees/' + this.state.id + '/calculate',requestOptions);
    const data = await response.json();
    this.setState({ loadingCalculate: false,netIncome: data });
  }
    async getEmployee(id) {
        this.setState({ loading: true,loadingCalculate: false });
        const token = await authService.getAccessToken();
        const response = await fetch('api/employees/' + id, {
          headers: !token ? {} : { 'Authorization': `Bearer ${token}` }
        });
    
        if(response.status === 200){
            const data = await response.json();
            this.setState({ id: data.id,fullName: data.fullName,birthdate: data.birthdate,tin: data.tin,typeId: data.typeId, loading: false,loadingCalculate: false });
        }
        else{
            alert("There was an error occured.");
            this.setState({ loading: false,loadingCalculate: false });
        }
      }

EmployeeController.cs

/// <summary>
        /// Refactor this method to go through proper layers and use Factory pattern
        /// </summary>
        /// <param name="id"></param>
        /// <param name="absentDays"></param>
        /// <param name="workedDays"></param>
        /// <returns></returns>
        [HttpPost("{id}/calculate")]
        public async Task<IActionResult> Calculate(int id,decimal absentDays,decimal workedDays)
        {
            var result = await Task.FromResult(StaticEmployees.ResultList.FirstOrDefault(m => m.Id == id));

            if (result == null) return NotFound();
            var type = (EmployeeType) result.TypeId;
            return type switch
            {
                EmployeeType.Regular =>
                    //create computation for regular.
                    Ok(25000),
                EmployeeType.Contractual =>
                    //create computation for contractual.
                    Ok(20000),
                _ => NotFound("Employee Type not found")
            };
        }
1

There are 1 best solutions below

0
AudioBubble On BEST ANSWER

You only set the absentDays and workedDays parameters in the request body, so you need to either decorate them with the [FromBody] attribute or add them as route or query parameters. See the Microsoft Model Binding in ASP.NET Core article for more details.