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
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:
And then use that as your parameter object:
You cant get value because you cant get it from html.You should get team name like this. Just add #.
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 useJSON.stringify(xxx)
to change the data type beforeajax
.Here is a demo worked:
View:
Controller:
result:
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.