当我在ASP.Net中使用jQuery发布时,WebApi接收空参数

时间:2012-10-12 07:09:24

标签: c# .net asp.net-web-api

所以我正在尝试构建一个简单的API,允许我创建客户,我在VS2012上使用ASP.NET Web API,我正在使用默认的项目配置。 这就是我所拥有的:

HTML

<h2 id="msg"></h2>
<form onsubmit="return submitCustomer()">
    <input type="text" name="name" id="name" />
    <input type="text" name="email" id="email" />
    <input type="text" name="phone" id="phone" />

    <input type="submit" value="Sign Up" />
</form>

<script type="text/javascript">
    function submitCustomer() {        
        $.ajax({
            url: '/api/customer',
            type: 'POST',
            datatype: 'json',
            success: function (newCustomer) {
                var msg = 'Welcome ' + newCustomer.Name;
                $('#msg').text = msg;
            }
        });
        return false;
    }
</script>

CONTROLER METHOD

// POST api/customer
public Customer Post(Customer customer)
{
     CustomerService customerService = new CustomerService();
     customerService.CreateCustomer(customer);
     return customer;
}

MODEL

public class Customer : BaseModel
{

    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private string _phone;

    public string Phone
    {
        get { return _phone; }
        set { _phone = value; }
    }

    private string _email;

    public string Email
    {
        get { return _email; }
        set { _email = value; }
    }

    private Region _region;

    public virtual Region Region
    {
        get { return _region; }
        set { _region = value; }
    }

    private List<Product> _products;

    public virtual List<Product> Products
    {
        get
        {
            if (_products == null)
            {
                _products = new List<Product>();
            }
            return _products;
        }
        set { _products = value; }
    }


    private List<CustomerPromotion> _customerPromotions;

    public virtual List<CustomerPromotion> CustomerPromotions
    {
        get
        {
            if (_customerPromotions == null)
            {
                _customerPromotions = new List<CustomerPromotion>();
            }
            return _customerPromotions;
        }
        set { _customerPromotions = value; }
    }

    private int? _regionId;
    public int? RegionId
    {
        get
        {
            return _regionId;
        }
        set
        {
            _regionId = value;
        }
    }

}

发生的事情是,当我提交表单时,我会使用POST方法,但客户为空,是否有人知道为什么会这样?

1 个答案:

答案 0 :(得分:2)

您缺少$ .ajax功能中的数据。

$.ajax({
  datatype:'json',
  data: yourformdata,
  ...
});