【问题标题】:ajax call not send the data to controllerajax 调用不将数据发送到控制器
【发布时间】:2023-02-02 15:55:04
【问题描述】:

我尝试使用 ajax 调用将数据从视图传递到控制器,但我在控制器中收到 null。在操作中,我的参数变为 null。

我的看法:

$(document).on('click','.btnsubmit', function (e) {
        e.preventDefault();
        var id = parseInt($(this).attr("id"));
        var value=$("#txt_"+id).val();
        debugger
        $.ajax({
            url: "/Home/AddResult",
            type :"POST",
            contentType: "application/json",
            async:false,
            
            data: JSON.stringify({"id":id,"value":value}),
            
                success: function (data) {
                alert("Result Saved");
                console.log(data.result);


            },
            error: function (err) {
                console.error(err);
            }
        })
    });

我的控制器:

 public IActionResult AddResult(int id,string value)
        {
            if(ModelState.IsValid)
            {
                test.Update(id, value);
            }
            return Json(new { result = true });
        }

【问题讨论】:

  • 您是否尝试将 [FromBody] 添加到您的参数中?
  • 是的,FromBody 和 FromForm 都不起作用

标签: jquery ajax asp.net-core-mvc


【解决方案1】:

您可以创建一个包含这些参数的模型,然后使用[FromBody]

public class TestA
        {
            public int id { get; set; }
            public string value { get; set; }

        }

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多