0

I have an angular client that has an angular JSON editor. I have to send the JSON data (from the editor) to a .NET Core Web API controller and there I have to perform tasks like writing it into a JSON file. How do I approach this? I need help and more with the controller.

1
  • You should add the relevant code you already have (in angular and in your controller) Commented Jun 18, 2020 at 11:42

1 Answer 1

1

I have to send the JSON data (from the editor) to a .NET Core Web API controller and there I have to perform tasks like writing it into a JSON file. How do I approach this?

To achieve the above requirement, you can refer to following code snippet.

Angular client

@ViewChild(JsonEditorComponent) editor: JsonEditorComponent;

options = new JsonEditorOptions();
data = {
  name: "fei",
  age: 28
};

constructor(private httpClient: HttpClient) {
  this.options.mode = "code";
  this.options.modes = ["code", "text", "tree", "view"];
  this.options.schema = schema;
  this.options.statusBar = false;
  this.options.onChange = () => console.log(this.editor.get());
}

InsertUser() {
  const updatedJson = this.editor.get();
  const headers = new HttpHeaders().set("Content-Type", "application/json");

  this.httpClient
    .post("https://xxxxx/Insert", JSON.stringify(updatedJson), {
      headers: headers,
      responseType: "text"
    })
    .subscribe(data => {
      console.log(data);
    });
}

Controller and Action

[HttpPost("/Insert")]
public async Task<IActionResult> InsertUser(User User)
{
    //...

    return Ok("success");
}

Model class User

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Test Result

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Fei Han, thank you so much for your help. Just one follow up question, here we have a model that is already defined. What if we we have to send a random JSON file. In that case, how will the controller action look like. Here you have already defined the User model. That way the controller can accept any JSON data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.