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

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

string team awlays returns null. i dont know whats the problem.
Searched for same issue in stackoverflow, but no one works for me

3

Answers


  1. It looks like you are sending in an object with the property "team", instead of just a raw string.

    You can create a request object as your parameter:

    public class AddTeamRequest
    {
        public string Team {get; set;}
    }
    

    And then use that as your parameter object:

    public JsonResult AddTeam(AddTeamRequest request)
    
    Login or Signup to reply.
  2. You cant get value because you cant get it from html.You should get team name like this. Just add #.

     function addTeam() {
        var teamName = $("#teamField").val();///this line
        $.ajax({
            type: "POST",
            url: 'AddTeam',
            contentType: "application/json;",
            data:
                { team: "HELLO PLEASE WORK" },
            success: function () {
                alert("URA");
            },
            error: function (error) {
                alert(error);
            }
        });
    };
    
    Login or Signup to reply.
  3. You use application/json,so you put the data into body,if you want to get the data in post method,you can use [FromBody].And the data you pass need to use JSON.stringify(xxx) to change the data type before ajax.
    Here is a demo worked:

    View:

    var team1 = "HELLO PLEASE WORK";
            var team = JSON.stringify(team1) ;
            $.ajax({
                type: "POST",
                url: 'AddTeam',
                contentType: "application/json;charset=utf-8",
                data: team,
                success: function () {
                    alert("URA");
                },
                error: function (error) {
                    alert(error);
                }
            });
    

    Controller:

    [HttpPost]
            public JsonResult AddTeam([FromBody]string team)
            {
                
                return Json(team);
            }
    

    result:
    enter image description here

    Or you can use contentType: "application/x-www-form-urlencoded",,so that you don’t need to use [FromBody] and don’t need to change the data type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search