在Ajax请求中使用JSON.stringify方法将数据转换为JSON格式,然后将其作为参数传递给razor页面处理程序。在razor处理程序中,使用Newtonsoft.Json包将JSON转换回原始对象。
以下是解决方法的代码示例:
JavaScript代码:
var dataToSend = null; var url = "/PageHandler";
$.ajax({ type: "POST", url: url, contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(dataToSend), success: function (response) { console.log(response); }, error: function (error) { console.log(error); } });
Razor页面处理程序代码:
public JsonResult OnPost(PageModel model) { var json = Request.Body; string requestBody = GetRequestBody(json);
if (!String.IsNullOrEmpty(requestBody))
{
model = JsonConvert.DeserializeObject(requestBody);
}
// Process data
return new JsonResult(model);
}
private string GetRequestBody(Stream body) { using (StreamReader reader = new StreamReader(body)) { return reader.ReadToEnd(); } }
注意:在此示例中,PageModel是一个简单的模型对象,其中包含要处理的数据。需要在内部定义PageModel类。
上一篇:Ajax将Null传递给控制器