如何将模型对象传递给Web API Post方法

时间:2016-02-08 15:37:20

标签: c# asp.net-mvc-4 asp.net-web-api asp.net-ajax

我想在MVC应用程序中将数据保存到数据库。我有下面的类调用webapi1服务post方法。这里Sample是一个模型对象。我有一个使用Sample对象的视图。我想使用服务调用将Sample Object数据惰化为db。

public SampleTestCreate(Sample)
{
    string uri = baseUri + "Test";
    using (HttpClient httpClient = new HttpClient())
    {
        Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(uri, new StringContent(JsonConvert.SerializeObject(Test)));
      //  Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(uri, Test);
        var data = response.Result.Content.ReadAsStringAsync().Result;
       return JsonConvert.DeserializeObjectAsync<Test>(response.Result.Content.ReadAsStringAsync().Result).Result;
     }
}

// POST api/Sample
public HttpResponseMessage PostSample(Sample Sample)
{
    if (ModelState.IsValid)
    {
        db.Samples.Add(Sample);
        db.SaveChanges();

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Sample);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Sample.SampleID }));
        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

这里我的服务帖子方法被调用,但是&#34; Sample&#34;对象的所有属性值都为null。模型对象绑定没有发生。

0 个答案:

没有答案