Kashuba Artur
Kashuba Artur

Reputation: 3

How can I send arguments into my controller ASP from JS?

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
}

Upvotes: 0

Views: 86

Answers (2)

Rimon Arif
Rimon Arif

Reputation: 36

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

Upvotes: 0

Melba L
Melba L

Reputation: 76

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

Upvotes: 2

Related Questions