0

I can't POST data from input fields as a object. I tried e.g. JSON.stringify({FactoryId: FactoryId.value}) but it doesnt work. If I input data in JSON.stringify({FatctoryId: '12345'}) it create object in database but with id=12345. I would like get value from input field and post them like an object. Could you help me?

class Create extends Component {        

      constructor() {
        super();
        this.state = {
          ProductId: '',
          FactoryId: '',
          Name: '',
          Description: '',
          Category: '',
          Availability: ''
        };
      }

      onChange = (e) => {
        const state = this.state
        state[e.target.name] = e.target.value ;
        this.setState(state);
      }




      post = () => {
          fetch('/api/Products',
              {
                  method: 'post',
                  headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json'
                  },
                  body: JSON.stringify()        
              });
      };        

      render() {
        const { ProductId, FactoryId, Name, Description, Category, Availability } = this.state;
        return (
          <div class="container">
            <div class="panel panel-default">
              <div class="panel-heading">
                <h3 class="panel-title">
                  ADD PRODUCT
                </h3>
              </div>
              <div class="panel-body">
                <h4><Link to="/fetch"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Products List</Link></h4>
                        <form onSubmit={this.post} name="form">
                  <div class="form-group">
                  <label for="isbn">FactoryId:</label>
                  <input type="text" class="form-control" name="FactoryId" value={FactoryId} onChange={this.onChange} placeholder="FactoryId" required/>
                  </div>                 
                  <button type="submit" class="btn btn-default">Submit</button>
                </form>
              </div>
            </div>
          </div>
        );
      }
    }

Product.cs

using System;
using MongoDB.Bson.Serialization.Attributes;

namespace Shop.Models
{
    public class Product
    {
        [BsonId]
        public Guid ProductId { get; set; }
        [BsonRequired]
        public string FactoryId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public int Availability { get; set; } = 0;
    }
}

ProductsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Shop.IRepository;
using Shop.Models;


namespace Shop.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProductRepository _productRepository;


        public ProductsController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        [HttpGet]
        public Task<string> Get()
        {
            return this.GetProduct();
        }

        public async Task<string> GetProduct()
        {
            var products = await _productRepository.Get();
            return Newtonsoft.Json.JsonConvert.SerializeObject(products);
        }

        [HttpGet("{id}")]
        public Task<string> Get(Guid id)
        {
            return this.GetProductById(id);
        }

        public async Task<string> GetProductById(Guid id)
        {
            var product = await _productRepository.Get(id) ?? new  Product();
            return Newtonsoft.Json.JsonConvert.SerializeObject(product);
        }


        [HttpPost]
        public async Task<string> Post([FromBody] Product product)
        {
            await _productRepository.Add(product);
            return "";
        }

        [HttpPut("{id}")]
        public async Task<string> Put(Guid id,[FromBody] Product product)
        {
            if (string.IsNullOrEmpty(id.ToString())) return "Invalid id!";
            return await _productRepository.Update(id, product);

        }

        [HttpDelete("Delete/{id}")]
        public async Task<string> Delete(Guid id)
        {
            if (string.IsNullOrEmpty(id.ToString())) return "Invalid id!";
            await _productRepository.Remove(id);
            return "";
        }

        [HttpDelete]
        public async Task<string> Delete()
        {
            await _productRepository.RemoveAll();
            return "";
        }


    }
}
4
  • Would you mind to show us the server side, please ? Commented Feb 15, 2019 at 14:56
  • Could you check now? Commented Feb 15, 2019 at 15:40
  • Okay, I was wondering about the "FromBody", but it's not missing. Anyway, is it normal that you have nothing a parameter at this line : "body: JSON.stringify()" ? Should it not be "body: JSON.stringify(this.state)" ? Commented Feb 15, 2019 at 16:35
  • Yeah, but it also doesnt work. Commented Feb 15, 2019 at 20:19

1 Answer 1

0

You did not input parameter for JSON.stringify() method. You try like this

(async () => {
  const rawResponse = await fetch('/api/Products', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(this.state)  
  });
  const content = await rawResponse.json();

  console.log(content); //log content
})();
Sign up to request clarification or add additional context in comments.

Comments

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.