首页 > 解决方案 > 发送 JSON 对象。如何设置简单的 .net 控制器方法来接收这种类型?

问题描述

目前我正在从看起来完全像这样的角度发送对象。

{"department":2,"note":"asdf","weekEnding":"2019-11-02T00:00:00"}

然后我在我的 .net 控制器中使用这个方法,看起来像这样。

    [HttpPost]
    [Route("Edit")]
    public void Edit([FromForm] CorpNotes newMessage)
    {

        //_SLGContext.Entry(newMessage).State = EntityState.Modified;
        //_SLGContext.SaveChanges();
    }

下面是我的 CorpNotes 模型

public class CorpNotes
{
    public string Department { get; set; }

    public string Note { get; set; }

    public string WeekEnding { get; set; }
}

我在我的 Post 方法 Edit() 中收到变量 CorpNotes newMessage 中的所有空值

为什么我的所有值都为空? slg-corp-notes.service.ts

  updateMessage(message: any) {
    console.log("at service")
    console.log(message)
    var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
    var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
    console.log(newMessage)
    console.log(JSON.stringify(newMessage))
    console.log(Params)

    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json;charset=UTF-8')

    let options = { headers: headers };

    return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options);
    //return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage))


  }

标签: javascriptc#.netjsonangular

解决方案


  1. JSON.stringify从您的 Angularhttp.post调用中删除。它应该只是能够识别一个对象。

  2. JSON 中的最后一个字段是日期,但 C# 模型需要一个字符串,也将其更改为日期。


推荐阅读