jquery - 使用 asp.net core 和 Jquery 从 ajax 请求将对象绑定(bind)到 asp mvc Controller

标签 jquery asp.net-mvc asp.net-core model-binding

我正在努力将 json 数据从 ajax 请求发布到 asp mvc Controller 方法,但由于某些未知原因,asp mvc 模型绑定(bind)器没有绑定(bind)它。

我尝试遵循此处发布的多个答案,包括以下内容

Post json object to ASP MVC doesn't work properly

但是我的 jQuery ajax 方法总是将 null 值发送到 asp mvc Controller 。

基本上,我试图通过 ajax 请求加载部分 View 。

Ajax 请求

var myData =
 {
        "Id": 7,
        "Name": "Name 1"
 };

  var obj = { 'test': myData };
  var val = JSON.stringify(obj);
  console.log(val);

  $.ajax({
    type: 'POST',
    dataType: 'html',
    url: '/Home/Partial',
    contentType: 'application/json',
    data: val,
    success: function (xhr, status, response) {
             console.log(response);
             $('#1').html(response.responseText);
         },
    error: function (err) {
        alert("error - " + err);
    }
   });

Controller 方法

[HttpPost]
public IActionResult Partial(Test test)
{
   return PartialView("_Test", test);
}

型号

public class Test
{
    public int Id;
    public string Name;
}

最佳答案

myData 足以绑定(bind)对象。

var myData = { Id: 7, Name: "Name 1" };
var val = JSON.stringify(myData);
console.log(val);

$.ajax({
  type: 'POST',
  dataType: 'html',
  url: '/Home/Partial',
  contentType: 'application/json',
  data: val,
  success: function (xhr, status, response) {
    console.log(response);
    $('#1').html(response.responseText);
  },
  error: function (err) {
    alert("error - " + err);
  }
});

您还应该考虑参数上的 [FromBody] 属性,以便模型绑定(bind)器知道检查模型的主体。

[HttpPost]
public IActionResult Partial([FromBody]Test test)  {
    return PartialView("_Test", test);
}

关于jquery - 使用 asp.net core 和 Jquery 从 ajax 请求将对象绑定(bind)到 asp mvc Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331925/

相关文章:

jquery datepicker 自动打开(但不应该)

c# - purecss.io 并包装一个 LabelFor

asp.net-mvc - 构建 MVC CMS

iis-7 - 如何在 IIS 经典模式池下托管 ASP.NET 5 (vNext) MVC 6 项目

c# - 使用 IdentityServer4 从单个客户端接受 Bearer 身份验证和 OpenIdConnect 时出现奇怪的行为

javascript - 如何从iframe标签中获取data-id值?

javascript - 我如何通过单击网站 Logo 打开和关闭左侧导航栏

jquery - 使用具有可变单元格数量的引导网格

c# - 参数类型 'Edm.String' 和 'Edm.Int32' 与此操作不兼容

c# - 您如何检查 ASP Core 类中的授权?