0

I am trying to make my .net core MVC website receive JSON that I send from a view through javascript. Sadly it seems the model is not being filled in with the data.

[HttpPost]
public ActionResult AddSubtitles(AddSubtitleSettingsModel model)
{
    /* do things and save to database */
    return RedirectToAction("Subtitling");
}

My model:

public class AddSubtitleSettingsModel
{
    public HashSet<string> from { get; set; }
    public HashSet<string> to { get; set; }
    public decimal startupRateLessThanOneMinute { get; set; }
    public decimal startupRateBetweenOneAndThreeMinutes { get; set; }
    public decimal pricePerSubtitle { get; set; }
    public decimal defaultRateTranslators { get; set; }
}

Request being sent to POST action: Request

I can tell the model is not being filled in because I put a breakpoint inside the action and I checked model, and everything was null/empty: Model empty

This is how I send my request from the javascript:

let fromValues: any = fromLanguages.getValue();
let toValues: any = toLanguages.getValue();
var data = {
    from: fromValues.map((l: any) => l.value),
    to: toValues.map((l: any) => l.value),
    startupRateLessThanOneMinute: Number($('#srLt1m').val()),
    startupRateBetweenOneAndThreeMinutes: Number($('#stBt13m').val()),
    startupRateBetweenThreeAndFiveMinutes: Number($('#stBt35m').val()),
    pricePerSubtitle: Number($('#pPS').val()),
    defaultRateTranslators: Number($('#dRT').val())
}

fetch('/Settings/AddSubtitles', {
    method: 'post',
    body: JSON.stringify(data)
}).then((response: any) => {
    console.log(response);
});

Any suggestions would be greatly appreciated.

nbokmans
  • 5,492
  • 4
  • 35
  • 59

1 Answers1

4

Try adding [FromBody] to your Method

[HttpPost]
public ActionResult AddSubtitles([FromBody]AddSubtitleSettingsModel model)
{
    /* do things and save to database */
    return RedirectToAction("Subtitling");
}
Tim B James
  • 20,084
  • 4
  • 73
  • 103