AlwaysNeedingHelp
AlwaysNeedingHelp

Reputation: 1945

Controller Action won't accept JSON post using JS Fetch API even with [FromBody] and Content-Type set

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?

Upvotes: 1

Views: 823

Answers (1)

Gowtham
Gowtham

Reputation: 71

Create Class the pass the data

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

then assign

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

Upvotes: 2

Related Questions