Im Fetching to change my Record and the value newInsert
is in the fetch true but in the Controller its false.
Fetch:
fetch('api/Test/UpdateOrInsertType', {
headers: { 'Content-Type': 'application/json' },
method: 'POST',
body: JSON.stringify({
'newInsert': newInsert //Console.log -> true
})
Controller:
[HttpPost("UpdateOrInsertType")]
public IActionResult UpdateOrInsertType([FromBody] bool newInsert)
// Debugger newInsert -> false
{
try
{
return Ok(Test.UpdateOrInsertType(newInsert));
}
catch (Exception ex)
{
return Conflict(ex);
}
}
CodePudding user response:
Json doesn't work properly with primitive types. If you wont to use json.stringify you have to create a ViewModel
public class ViewModel
{
public bool NewInsert {get; set;}
}
and action
[HttpPost("UpdateOrInsertType")]
public IActionResult UpdateOrInsertType([FromBody] ViewModel model)
{
bool newInsert=model.NewInsert
or you can remove { 'Content-Type': 'application/json' }
fetch('api/Test/UpdateOrInsertType', {
method: 'POST',
body: { newInsert: newInsert }
})
and remove [FromBody]
[HttpPost("UpdateOrInsertType")]
public IActionResult UpdateOrInsertType( bool newInsert)
CodePudding user response:
In this case you should not use JSON.stringify
.
Simply pass the raw javascript object to fetch
body
:
fetch('api/Test/UpdateOrInsertType', {
method: 'POST',
body:
{
newInsert: newInsert
}
});
Now on server side it will be recognized as a bool
property.