3

I'd like to pass an AJAX parameter to the MVC Controller in ASP .Net Core 2.

This is what i tried :

function getMatchesFromChampionshipAsync(championship) {
    console.log(championship);
    $.ajax({
        url: "/Bets/Matches",
        type: "POST",
        data: { "championship": championship },
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        success: function (response) {
            alert(response)
        }
    })
}

I'm sure that the parameter championship is correct (I also tried to log it), but the Controller always receives null.
This is the Controller Action Method code:

[HttpPost]
    public IActionResult Matches([FromBody] string championship) {
        return Json(championship);
    }

The browser also alerts null. I also read other questions about it but no one worked.

ollaw
  • 2,086
  • 1
  • 20
  • 33

4 Answers4

4

I solved using a Class with a single property called Championship :

public  class Value {
        public String Championship { get; set; }
}

and using it as Model in the Action method :

[HttpPost]
public IActionResult Matches([FromBody] Value ch) {
    return Json(ch.Championship);
}

I don't know if there is a simpler way.

ollaw
  • 2,086
  • 1
  • 20
  • 33
1

Lately, I have really liked using a formData object in javascript to pass data from xhr/ajax to post to MVC actions. Here is an example:

    var nameFormDataHere = new FormData();
    nameFormDataHere.append("championship", championship);
    $.ajax({
    url: "/Bets/Matches",
    type: "POST",
    data: nameFormDataHere,
    dataType: "json"
    processData: false,
    contentType: false,
    success: function (response) {
        alert(response);
    }
});

Just like your example above you will need to create a model(a class) with a property and have the data annotation [HttpPost] above the action that ajax is posting to, with the new model(class) as a parameter into the action. This is from your example above:

Model:

    public  class Value{
        public String Championship { get; set; }
    }

Action:

    [HttpPost]
    public IActionResult Matches(Value ch) {
        return Json(ch.Championship);
    }

I have used this several times and have never had to use the [FromBody] annotation for this to work.

Adam
  • 395
  • 4
  • 9
0

Try removing the "contentType" qualifier in your ajax statement or simply wrap your parameter in JSON.stringify ie. data:JSON.stringify(championship).

Leigh.D
  • 463
  • 5
  • 13
-1

Try adding traditional: true

function getMatchesFromChampionshipAsync(championship) {
console.log(championship);
$.ajax({
    url: "/Bets/Matches",
    type: "POST",
    data: { "championship": championship },
    traditional: true,
    dataType: 'json',
    contentType: 'application/json; charset=UTF-8',
    success: function (response) {
        alert(response)
    }
})}
Sanchal Kunnel
  • 539
  • 6
  • 8