簡體   English   中英

當我在ASP.Net中使用jQuery發布時,WebApi接收空參數

[英]WebApi receiving null parameter when I post using jQuery in ASP.Net

所以我正在嘗試構建一個簡單的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方法,但客戶為空,是否有人知道為什么會發生這種情況?

您缺少$ .ajax函數中的數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM