Web API模型属性为空 [英] Web API Model properties are null

查看:74
本文介绍了Web API模型属性为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器能够创建模型对象,但是所有与模型相关的属性都被分配为空值

My Controller is able to create the model object but all the properties related to model and assigned to null values

环境:VS 2010,最新的ASP.NET MVC RC,jQuery 1.7.1

Environment : VS 2010, ASP.NET MVC RC latest, jQuery 1.7.1

以下是Web API控制器代码

Following is the Web API Controller code

public class Customer
{
    public string Name { get; set; }
    public string City { get; set; }
}
public class UserController : ApiController
{
    public Customer Post(Customer user)
    {
        return user;
    }
}

以下是ajax调用代码

Following is the ajax calling code

$.ajax('/api/user',
{
  ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  dataType: 'json',
  type: 'POST',
  data: JSON.stringify({ "Name": "Scott", "City": "SC" })
});

控制器确实创建了模型"Customer"对象,但"Name"和"City"属性均为空.

Controller does create the model "Customer" object but both "Name" and "City" properties are null.

这是怎么了?

我已经在该网站上阅读了许多类似的问题,但是找不到解决方法.

I have read many similar issues on this site but could not find the solution.

推荐答案

This blog here gives a good idea about how Model Binding differs in ASP.NET Web project and a ASP.NET Web API project.

在我正在从事的项目中,我遇到了类似的问题,并添加了一个显式的ModelBinding属性,使属性值保持不变

I was facing a similar issue in the project I was working on and adding a explicit ModelBinding attribute made the property values stick

请求的数据:

var customer  = { Name : "customer Name", City : "custome City" }

$.ajax({ 
   url : ...
   type: ...
   data : customer
});

请求类别:

public class Customer
{
    public string Name { get; set; }
    public string City { get; set; }
}

控制器:

public class UserController : ApiController
{
    [HttpGet]
    public Customer Get([ModelBinder] Customer user)
    {
        // fetch from whereever
    }
}

这篇关于Web API模型属性为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆