MVC控制器参数始终为null

时间:2016-05-03 09:15:01

标签: c# ajax asp.net-mvc asp.net-ajax

我的ajax代码

function gonder() {
    var params = {
        DonationInfo: {
            name: $('#name').val(),
            lastname: $('#lastname').val(),
            phone: $('#phone').val(),
            type: $('#type').val(),
            amounth: $('#amounth').val(),
            quentity: $('#quentity').val()
        }
    };
    $.ajax({
        url: '@Url.Action("Index", "Benafactor")',
        type: 'POST',
        async: true,
        data: JSON.stringify(params),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            alert(data.success);
            $('#target').html(data);
        },
        error: function () {
            alert("error");
        }
    });
}

MY Controller

   [System.Web.Http.HttpPost]
    public ActionResult Index([FromBody] Mymodel data)
    {
        return Json(new { success = true });

    }

我也试过字符串

这是Mymodel

  public class Mymodel
{
    public string name { get; set; }
    public string lastname { get; set; }
    public string phone { get; set; }
    public string type { get; set; }
    public string amounth { get; set; }
    public string quentity { get; set; }
}

我努力了,寻找所有相同的问题,但没有任何工作对我来说请帮助我可以看到请求有效负载中的数据,但无法将参数输入控制器

4 个答案:

答案 0 :(得分:3)

当您将对象(params))序列化为json时,mvc ActionResult参数模型(Mymodel)和对象(params))的结构需要是相同的结构,在您的代码中paramsMymodel的结构不一样。使其相同可以解决问题

var params = {
            name: $('#name').val(),
            lastname: $('#lastname').val(),
            phone: $('#phone').val(),
            type: $('#type').val(),
            amounth: $('#amounth').val(),
            quentity: $('#quentity').val()
       };

答案 1 :(得分:1)

使用它:

var params = {
        name: $('#name').val(),
        lastname: $('#lastname').val(),
        phone: $('#phone').val(),
        type: $('#type').val(),
        amounth: $('#amounth').val(),
        quentity: $('#quentity').val()
    }

对于复杂对象,使用变量比在ajax方法中包含它更好

答案 2 :(得分:0)

JSON.stringify不是必需的data: params.DonationInfo

答案 3 :(得分:0)

function gonder() {
    var data= {

            name: $('#name').val(),
            lastname: $('#lastname').val(),
            phone: $('#phone').val(),
            type: $('#type').val(),
            amounth: $('#amounth').val(),
            quentity: $('#quentity').val()

    };
    $.ajax({
        url: '@Url.Action("Index", "Benafactor")',
        type: 'POST',
        async: true,
        data: JSON.stringify(params),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            alert(data.success);
            $('#target').html(data);
        },
        error: function () {
            alert("error");
        }
    });
}

您的控制器将如下所示

[HttpPost]
    public ActionResult Index(Mymodel data)
    {
        return Json(new { success = true });

    }