Home > Mobile >  Controller Action won't accept JSON post using JS Fetch API even with [FromBody] and Content-Ty
Controller Action won't accept JSON post using JS Fetch API even with [FromBody] and Content-Ty

Time:11-17

All other posts I've read haven't helped me on this topic (telling me to put [FromBody] or set the content type in the header).

My js function is:

async function GetEditModalHTML(productPriceGroupID) {
    const data = {
        ProductPriceGroupID: productPriceGroupID
    }
    const response = await fetch('/promotions/productprice/edit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
        },
        body: JSON.stringify(data)
    });
    
    return await response.text();
}

And the function definition in the controller:

[HttpPost]
public async Task<IActionResult> Edit([FromBody] int productPriceGroupID)

Debugging in Rider I know the action is properly being called. In chromes network tab I can see the payload as:

enter image description here

But no matter what I try to do, the value of productPriceGroupID is always 0. Why?

CodePudding user response:

Create Class the pass the data

    class ProductDetails{
public int productPriceGroupID {get;set;}
}

then assign

[HttpPost]
public async Task<IActionResult> Edit([FromBody] ProductDetails productPriceGroupID)
  • Related