V
V
VanilaSpirit2020-07-02 15:58:17
ASP.NET
VanilaSpirit, 2020-07-02 15:58:17

ASP NET Core why is Ajax POST always null?

<input type="text" class="form-control" id="teamField"/>
            <input type="button" value="Добавить"  class="btn btn-default" onclick="addTeam()"/>


function addTeam() {
    var teamName = $("teamField").val();
    $.ajax({
        type: "POST",
        url: 'AddTeam',
        contentType: "application/json;",
        data:
       {
            team: "TEST" ,
       },
        success: function () {
            alert("URA");
        },
        error: function (error) {
            alert(error);
        }
    });
};


[HttpPost]
        public IActionResult AddTeam(string team)
        {
            teamRepository.Add(new Team { IsDelete = false, Name = team });
            teamRepository.SaveChanges();
            return Json(new { Result = "Success" });
        }


The controller always receives Null, I don't understand what could be the reason..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2020-07-03
@VanilaSpirit

In the request, you pass an object that has a team field with the value test. And the controller does not accept an object, but simply a value. Therefore, in the request parameters, you can simply give the value data: test. Or in the controller, change the parameter to an object
class Param { string team }
AddTeam(Param team)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question