【问题标题】:How to send class parameters to controller如何将类参数发送到控制器
【发布时间】:2016-03-22 06:42:45
【问题描述】:

我的班级;

public class Disciplines
{
    public int Id { get; set; }

    public string Name { get; set; }
}

我的控制器;

public void test (Disciplines discipline)
{

}

并使用 ajax 我想将参数发送到测试控制器。

我的 javascript 是 ;

    var disciplines = {Id:1, name:"white"};
            $.ajax({

                type: "POST",
                url: "test",
                data: { disciplines:disciplines },
                dataType: "Json",
                success: function (response) {
                },
                beforeSend: function () {


   showIndicator();
            },
            error: onFailure,

        });

当我调试它时,控制器参数始终为空。 我怎样才能成功地做到这一点。非常感谢。

【问题讨论】:

  • 你试过data: disciplines,吗?
  • 您必须与“Id”、“Name”具有相同的对象参数名称
  • 在您的 ajax 中,您正在编写 dataType: "Json",但您期待的是 Disciplines,这是一个自定义对象。您必须手动接收 JSON 并将其解析为您的对象

标签: javascript jquery ajax parameter-passing


【解决方案1】:

问题是因为模型绑定器将在请求中寻找idname 属性,而不是disciplines。试试这个:

var disciplines = {
    id: 1, 
    name: "white"
};

$.ajax({
    type: "POST",
    url: "test",
    data: disciplines,
    dataType: "json",
    success: function (response) {
    },
    beforeSend: function () {
        showIndicator();
    },
    error: onFailure,
});

【讨论】:

    【解决方案2】:

    你的代码应该是

     var disciplines = {"Id":1, "Name":"white"};
    
    $.ajax({
    
                    type: "POST",
                    url: "test",
                    data: { disciplines:disciplines },
                    dataType: "Json",
                    success: function (response) {
                    },
                    beforeSend: function () {
    
    
       showIndicator();
                },
                error: onFailure,
    
            });
    

    控制器

    [HttpPost]
    public void test (Disciplines discipline)
    {
    
    }
    

    必须具有与 中相同的参数名称

    【讨论】:

    • 我认为这是因为将对象中的参数名称用引号括起来不会有任何区别。模型绑定器将寻找 IdName 属性,而不是 disciplines
    • @RoryMcCrossan 它们是Namename 的区别。这不绑定到参数名称。
    • 鉴于 OP 在 ASP.Net MVC 中工作(鉴于代码结构和他之前的问题),这没什么区别 - 模型绑定器不区分大小写。
    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 2016-04-03
    • 2020-03-25
    • 1970-01-01
    • 2021-05-17
    • 2013-05-03
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多