用于插入具有复杂类型的数据的Web Api POST始终为null

时间:2016-02-03 04:59:06

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api2

我对Web-Api概念很陌生。尝试使用Microsoft提供的基本项目插入数据(将简单的测试客户端添加到ASP.NET Web API帮助页面)。

http://blogs.msdn.com/b/yaohuang1/archive/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page.aspx

下面是将数据插入Headoffice表的代码。(HeadofficeID int,HeadofficeName varchar(50),Notes varchar(1000),Isactive bit)

[POST("create")]
        public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
        {
            if (_headOfficeBLL.Insert(headOffices) > 0)
                return Request.CreateResponse(HttpStatusCode.Created, headOffices);
            else
                return Request.CreateResponse(HttpStatusCode.BadRequest, headOffices);
        }

Headofficemodel Class

public partial class HeadOfficeModel : AtlAuthenticationModelBase
    {
        public int HeadOfficeId { get; set; }
        public string HeadOfficeName { get; set; }
        public string Notes { get; set; }
        public bool IsActive { get; set; }
    }

在前端,当我尝试从URI或Body发送数据时,只有空值插入。虽然我在Headoffice模型中看到的所有调试都是空值。下面是我尝试插入数据的不同方法

1) {"HeadOfficeName":"TestHO1", "Notes":"notes", "IsActive":true}
2) {"TestHO1", "notes", true}
3) ={"headOffices":{"HeadOfficeName":"TestHO1","Notes":"notes","IsActive":false}}

并尝试更改以下代码

public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
public HttpResponseMessage Post([FromBody]HeadOfficeModel headOffices)
public HttpResponseMessage Post([ModelBinder]HeadOfficeModel headOffices)

一直试图解决这个问题。当我将数据作为复杂类型发送时,它不作为单独的参数工作(更改接受参数的方法)其工作正常

  public int Post(string Name, string Notes, bool Active)
    {
        HeadOfficeModel objHOM = new HeadOfficeModel();
        objHOM.HeadofficeName = Name;
        objHOM.Notes = Notes;
        objHOM.IsActive = Active;
        return _headOfficeBLL.Insert(objHOM);
    }

下面是插入

时我想要的html代码
<script>
  testClientModel = {
    HttpMethod: '@Model.ApiDescription.HttpMethod',
    UriPathTemplate: @Html.Raw(Json.Encode(Model.ApiDescription.RelativePath)),
    UriParameters: [
            @foreach (var parameter in Model.ApiDescription.ParameterDescriptions)
            {
              if (parameter.Source == System.Web.Http.Description.ApiParameterSource.FromUri)
              {
                    @:{ name: "@parameter.Name", value: "" },
                }
            }
    ],
    Samples: {
      @Html.Raw(@String.Join(",", Model.SampleRequests.Select(s => String.Format("\"{0}\": \"{1}\"", s.Key, HttpUtility.UrlEncode(s.Value.ToString()))).ToArray()))
    },
    BaseAddress: '@applicationPath'
  };
</script>

你能帮助我在哪里出错。附上截图。

在URI和Body中输入,只是为了表明我尝试了不同的方式。 enter image description here

0 个答案:

没有答案