0

I am using ASP.NET

I want to send some data into my controller (which set this date in DataBase) from JS. I have tried using "fetch" but object is null.

MyController name: HomeController,

My Action: ResultPage,

Data which I want to send: testResult

P.S I use [FromBody] from System.Web.Http;

console.log(testResult); // have some data
fetch('/Home/ResultPage',
    {
        method: 'post',
        body: JSON.stringify(testResult)
    })
[System.Web.Mvc.HttpPost]
public void ResultPage([FromBody] TestResult testResult)
{
      // testResult is null
      //some code here
}
Pavel Tupitsyn
  • 8,393
  • 3
  • 22
  • 44
  • 1
    how are you setting the value of `testResult` in your javascript code? and what is the class definition for `TestResult` in your api? – jtate Sep 29 '19 at 23:18
  • Please show us `TestResult` class and the JSON you're sending, `testResult`, from the js console – haldo Sep 29 '19 at 23:35
  • I guess this is help you: [link](https://stackoverflow.com/questions/22741943/web-api-post-body-object-always-null) – Guilherme Martin Sep 30 '19 at 01:51

2 Answers2

2
var data = {
    name: 'John'          
};     
var response = fetch('Home/ResultPage', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(data)
});

[HttpPost]
public void ResultPage([FromBody]Parameter parameter)
{
    //code here
}

public class Parameter
{
   public string name { get; set; }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Melba L
  • 76
  • 3
0

If there is a required property in you model class, it must pass the required property through your JS code into the Action Method.

Rimon Arif
  • 36
  • 4