SendData: function () {
var jasonStr = JSON.stringify(GamePlayedObj);
console.log(jasonStr);
$.ajax({
type: "POST",
async: false,
url: '@Url.Action("GamesSoFar", "AllCards")',
dataType: "json",
data: jasonStr,
contentType: "application/json; charset=utf-8"
});
}
[Route("Output")]
[HttpPost]
public ActionResult GamesSoFar(string jasonStr) {
string j = jasonStr;
string a = "";
GameInfo InfoOfTheLastGame = JsonConvert.DeserializeObject<GameInfo>(jasonStr);
_context.Add(InfoOfTheLastGame);
_context.SaveChanges();
var AllGames = _context.AllGames.Include(g => g.AllGames).ToList();
return View(AllGames);
}
我正在使用Asp.net核心webApi。我在函数控制器上使用的参数为null而不是json字符串。.j和a变量是出于调试原因,因此有任何想法吗?
您的代码将jasonStr
放入请求主体,因此无法在控制器中获取数据。如果要获取jasonStr,则可以使用[FromBody]
指定应使用请求主体绑定参数或属性并使用GameInfo jasonStr
而不是string jasonStr
绑定数据。
这里是一个演示作品:
GameInfo:
public class GameInfo
{
public string name { get; set; }
public int price { get; set; }
}
查看:
<div>
<button onclick="SendData()">SendData</button>
</div>
@section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
var GamePlayedObj = {};
GamePlayedObj.name = "game1";
GamePlayedObj.price = 10;
function SendData() {
var jasonStr = JSON.stringify(GamePlayedObj);
console.log(jasonStr);
$.ajax({
type: "POST",
async: false,
url: '@Url.Action("GamesSoFar", "AllCards")',
dataType: "json",
data: jasonStr,
contentType: "application/json; charset=utf-8"
});
}
</script>
}
控制器:
[Route("Output")]
[HttpPost]
public ActionResult GamesSoFar([FromBody]GameInfo jasonStr)
{
string a = "";
return View("OutPut");
}
结果: