ajax传递对象参数,后台使用FromBody接收对象参数


后端:

1、Modal:创建一个模型参数对象usermsg

public class usermsg
    {
        public string username { get; set; }

        public string password { get; set; }
    }

2、Controllers:将该对象类型作为参数类型

 

前端:

1、HTML:添加一个按钮button3

 

 

2、javascript事件:为button3添加一个事件

与传递字符串相比有两个不同点:

  其一:ajax对象参数多了一个属性contentType,值为application/json

  contentType:'application/json'

  其二:data参数中需要将对象序列化为json字符串

  data:JSON.stringify({username: 'zhangsan', password: '123456789'})
$('#btnGetUser').click(function(){
        $.ajax({
            url:'http://localhost:53179/values/api/getuser',
            dataType:'json',
            type:'Post',
            contentType:'application/json',
            data:JSON.stringify({username: 'zhangsan', password: '123456789'}),
            success:function(res){
                console.log(res)
                if(res!=null){
                    $('#name').prop('value',res.username);
                    $('#age').prop('value',res.age);
                }
            }
        })
    });

 

测试:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM