简体   繁体   中英

ASP.NET Core - API multiple parameters

I have an AJAX call wherein the body has 3 parameters

  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 });
}

The parameters came from a form that was written in React.js

<div className="form-row">

{ 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>

Now when I debug in the equivalent endpoint, only the ID parameter has value, the rest returns 0.

   public async Task<IActionResult> Calculate([FromBody]int id, Decimal absentDays, Decimal workedDays)
    {
            //implementation
    }

May I ask how can I go about having the three parameters available? Removing the ID is not possible as it is one of my required parameters. The JS code was already written that way but I am open to any suggestions.

You can use get request , it would be simplieer, but if you still want to post you will have to create view model

public DaysViewModel
{
public int Id {get; set;}
public int AbsentDays {get; set;} 
public int WorkedDays {get; set;}
}

and fix the action

public async Task<IActionResult> Calculate([FromBody] DaysViewModel viewModel)
    {
            //implementation
    }

javascript

const token = await authService.getAccessToken();
const requestOptions = {
    method: 'POST',
    headers: !token ? {} : { 'Authorization': `Bearer ${token}`,'Content-Type': 'application/json' },
    body: { viewModel:  {id: this.state.id, absentDays: this.state.absentDays, workedDays: this.state.workedDays}}
};
const response = await fetch('api/employees/calculate',requestOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM