【问题标题】:ASP.NET Core MVC posting a model to controller using ajaxASP.NET Core MVC 使用 ajax 将模型发布到控制器
【发布时间】:2018-10-17 22:17:27
【问题描述】:

我正在尝试使用 ajax 帖子将代表模型的 javascript 对象发布回控制器。但是,模型始终显示为 null。

有问题的型号如下

public class Product
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required and must not be empty.")]
    [StringLength(200, ErrorMessage = "Name should not exceed 200 characters.")]
    public string Name { get; set; }

    public DateTime Created { get; set; }

    [Required(ErrorMessage = "Price is required and must not be empty.")]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }
}

ajax 调用看起来像这样

$('#btnSaveNewProduct').click(function (e) {
                e.preventDefault();
                var form = $('#frmNewProduct');
                if (form.valid()) {
                    var data = { // to be replaced with form values
                        Name: 'Bob',
                        Price: 34
                    };
                    //ajax call to save product
                    $.ajax({
                        type: "POST",
                        url: "@Url.Action("AddProduct", "Admin")",
                        contentType: "application/json",
                        dataType: "json",
                        data: data,
                        success: function (response) {
                            alert('done');
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                }
            });

控制器方法如下所示

    [HttpPost]
    public JsonResult AddProduct([FromBody] Product product)
    {
        bool success = false;
        // save product
        success = true;
        return new JsonResult(success);
    }

任何见解将不胜感激。

【问题讨论】:

标签: c# jquery ajax asp.net-core


【解决方案1】:

要让您的代码按预期工作,请对您的代码进行以下三项修改。

  • 从 Ajax 调用中删除:dataType: "json"
  • 从 Ajax 调用中删除:data:data
  • 在 Ajax 调用中,添加:data:JSON.stringify(data)

注意事项:

  1. 当您使用[FromBody] 属性时,Content-Type 值确定 ASP.NET Core MVC 框架用于参数绑定的格式化程序。

  2. 由于您的 Content-Typeapplication/json,因此应该将 原始 JSON 字符串而不是 JSON 对象作为数据传递。因此,请申请JSON.stringify

  3. 请参阅此参考:Parameter Binding Using [FromBody] Attribute

【讨论】:

    【解决方案2】:

    我发现以下工作:

        $.ajax({
            method: "POST",
            data: { "Name": "bob", "Price": 10},
            url: "@Url.Action("AddProduct", "Admin")",
            success: function (data) {
                //success login
            },
            error: function (data) {
                alert('error' + data.status);
            }
        });
    

    在 ajax 调用中无需提及 dataType 和 contentType。您的控制器将如下所示:

    [HttpPost]
    public ActionResult AddProduct(Product product)
    {
        //You logic will be here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2013-01-13
      相关资源
      最近更新 更多