0

所以我正在尝试构建一个简单的 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>

控制器方法

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

模型

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 方法但客户为空,有人知道为什么会发生这种情况吗?

4

1 回答 1

2

您在 $.ajax 函数中缺少数据。

$.ajax({
  datatype:'json',
  data: yourformdata,
  ...
});
于 2012-10-12T07:13:01.413 回答