1、view层中ajax写法:
function Add2() { var model = new Object(); model.UserName = $(‘#UserName‘).val(); model.Age = 20; model.ID = 1; //提交 $.ajax({ contentType: "application/json", //必须有,表示提交的数据类型 type: "post", url: ‘ @ViewBag.WebApiUrl/Class/CreateSubmit3/‘, cache: false, data: JSON.stringify(model), // dataType: "json", error: function (jqXHR, textStatus, errorThrown) { if (jqXHR.status == ‘401‘) { //alert("登录过期,请重新登录"); } else { alert("添加失败"); } }, success: function (result) { // alert(result.ErrMsg); //location.href = ‘@ViewBag.WebApiUrl/home/index‘; }, beforeSend: function (xhr) { //xhr.setRequestHeader("Authorization", "Bearer " + $.cookie(‘access_token‘)); } }); }
2、mvc中控制器的写法。
public JsonResult CreateSubmit3(MyClass.Models.MyClass model) { //string aa = UserName; return Json(model); }
model的写法:
namespace MyClass.Models { public class MyClass { [Required] [Display(Name = "自动编号")] public int ID { set; get; } [Required] [Display(Name = "姓名")] public string UserName { set; get; } [Required] [Display(Name = "年龄")] public int Age { set; get; } } }
总结:
主要是看http的请求头中的 [contentType],如果ajax里没有指定属性 contentType,则默认为: application/x-www-form-urlencoded; 表示为表单方式。这种的在mvc控制器中就是使用这样的来接值:
public JsonResult CreateSubmit2(string UserName) { string aa = UserName; return Json("{‘a‘:‘1‘}"); }
如果,contentType指定为:application/json,则表示向服务器发送一个json串,上面那个例子里,就是发送这样的一个json串:
{"UserName":"99","Age":20,"ID":1}
原文地址:https://www.cnblogs.com/25miao/p/11345761.html
时间: 2024-10-01 21:43:47