Fajar Pratama
Fajar Pratama

Reputation: 19

Fetch from body return null into controller

Why does [FromBody] fetch value always return null value. I have tried everything but nothing has worked, maybe you have a better idea? I am stuck with this code.

This is my JavaScript:

const DetailSewa = barangSewa;

  const sewa = {
    NotaSewa: $("#notaSewa").val(),
    PelangganId: $("#cboSearchPelanggan").val(),
    TempatAcara: $("#txtTempatAcara").val(),
    TanggalAcara: $("#txtTanggalAcara").val(),
    OngkosKerja: $("#ongkosKerja").val(),
    OngkosKirim: $("#ongkosKirim").val(),
    OngkosCuci: $("#ongkosCuci").val(),
    SisaBayar: $("#sisaBayar").val(),
    UangMuka: $("#uangMuka").val(),
    TotalBayar: $("#totalBayar").val(),
    TipeDokumen: $("#cboSearchDokumen").val(),
    DetailSewa: DetailSewa,
  };

  $("#btnSimpan").closest("div.card-body").LoadingOverlay("show");

  fetch("/Transaksi/CreateSewaPeralatan", {
    method: "POST",
    headers: { "Content-Type": "application/json;charset=utf-8" },
    body: JSON.stringify(sewa),
  })
    .then((response) => {
      $("#btnSimpan").closest("div.card-body").LoadingOverlay("hide");
      return response.ok ? response.json() : Promise.reject(response);
    })
    .then((responseJson) => {
      if (responseJson.State) {

        swal("Terdaftar !", "Nota : " + $("#notaSewa").val(), "sukses");
      } else {
        swal("Maaf", "Sewa barang gagal terdaftar", "error");
      }
    })
    .catch((error) => {
      $("#btnSimpan").closest("div.card-body").LoadingOverlay("hide");
    });

my controller :

[HttpPost]
        public IActionResult CreateSewaPeralatan([FromBody] Sewa model)
        {
            ResponseSewa<Sewa> gResponse = new ResponseSewa<Sewa>();
            try
            {
                _transaksiService.CreateSewa(model);

                gResponse.State = true;
                gResponse.Object = model;

            }
            catch (Exception ex)
            {
                gResponse.State = false;
                gResponse.Message = ex.Message;
            }
            return StatusCode(StatusCodes.Status200OK, gResponse);
        }

My config Json Serialization:

services
                .AddMvc()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                });

I hope the fetch can pass the value into controller

Upvotes: 1

Views: 903

Answers (1)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22457

Why does [FromBody] fetch value always return null value. I have tried everything but nothing has worked, maybe you have a better idea?

I have reproduced your issue. You are getting null value on your controller because of your options.JsonSerializerOptions.PropertyNamingPolicy I am not sure why you have intented to set it as null. Either you should set to JsonNamingPolicy.CamelCase if you want to restrict CamelCase or just get rid of that.

Set to null means if anything doesn't matched it will always be empty. Thus, you are getting null value within your controller. You could modify as following:

Program.cs:

builder.Services.AddControllersWithViews().AddJsonOptions(options =>
{
    
    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
})

Note: If you don't want to set JsonNamingPolicy.CamelCase just ommit or comment the full line.

Sample Model:

 public class Sewa
        {
         
            public string NotaSewa { get; set; }
            public int PelangganId { get; set; }
            public string TempatAcara { get; set; }
        }

Controller:

        [HttpPost]
        public IActionResult CreateSewaPeralatan([FromBody] Sewa model)
        {
           
            return StatusCode(StatusCodes.Status200OK);
        }

Javascript:

const sewa = {
                NotaSewa: "NotaSewa Value From Client Side",
                PelangganId: 101,
                TempatAcara: "TempatAcara",
            };

            console.log(sewa);

             fetch("http://localhost:5094/JavascriptPost/CreateSewaPeralatan", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify(sewa),
            });

Output:

enter image description here

Note: If you would like to know more details on JSON property naming policy, you could check our official document here

Upvotes: 1

Related Questions