Skip to main content
 首页 » 编程设计

c#之MVC Controller 参数始终为空

2024年02月05日1052php

我的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"); 
        } 
    }); 
} 

我的 Controller

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

我也试过用字符串

这是我的模型

  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; } 
} 

我努力尝试,寻找所有相同的问题,但对我没有任何帮助,请帮助我可以看到请求有效负载中的数据,但无法将参数输入 Controller

请您参考如下方法:

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

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