Search code examples
asp.net-coreasp.net-core-webapiasp.net-ajax

Ajax POST not working without parameters in the URL


Google apparently is not my friend as I have tried many of the suggestions found, yet, none have worked for me.

I have 2 simple inputs as follows:

<form id="form">
<fieldset id="frmTest">
    <div class="form-outline">
        @Html.TextBoxFor(m => m.TextBox1, new { @id = "TextBox1", @class = "form-control" })
        @Html.LabelFor(m => m.TextBox1, new { @class = "form-label" })
    </div>
    <div class="form-outline mb-4">
        @Html.TextBoxFor(m => m.TextBox2, new { @id = "TextBox2", @class = "form-control" })
        @Html.LabelFor(m => m.TextBox2, new { @class = "form-label" })
    </div>
</fieldset>
</form>

As well as the JS:

$("#SaveTest").click(function (e) {
e.preventDefault();

var data = {

    TextBox1: $('#TextBox1').val(),
    TextBox2: $('#TextBox2').val(),

};

$.ajax({
    type: "POST",
    url: "http://localhost/api/api/ConfigurationManagement/TestAjax",
    data: JSON.stringify(data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    
    success: function (result) {
        alert(result.message);
    },
    error: function (response) {
        alert(response);
    }
});

Controller:

[HttpPost]
public async Task<ActionResult> TestAjax(string TextBox1, string TextBox2)
{

    Test model = new Test();

    model.TextBox1 = TextBox1;
    model.TextBox2 = TextBox2;

    _applicationDbContext.Test.Add(model);

    try
    {
        await _applicationDbContext.SaveChangesAsync();
        return Ok(new UserManagerResponse { Status = "Success", Message = "Successfully added test" });
    }
    catch (Exception ex)
    {
        return BadRequest(new UserManagerResponse { Status = "Failed", Message = ex.ToString() });
    }

}

When I click SaveTest button, I see the response as Bad Request indicating the following as if the parameters are not being passed:

{"errors":{"TextBox1":["The TextBox1 field is required.", "TextBox2":["The TextBox2 field is required."]}

On to the weird part, if I change the "url" and add the parameters at the end, it allows it to work.

url: "http://localhost/api/api/ConfigurationManagement/TestAjax?textBox1=" + $('#TextBox1').val() + "&TextBox2=" + $('#TextBox2').val(),

Though this question may appear to be a duplicate, each of our scenarios are different. I'd like to do it WITHOUT using the parameters in the URL, I just don't understand why it is not working for me without the parameters in the URL.

Thanks


Solution

  • Action parameters are by default bound to query parameters. In order to bind parameters from post body you need to accept a class parameter with TextBox1 and TextBox2 as properties instead.

    public class TxtModel
    {
        public string TextBox1 { get; set; }
        public string TextBox2 { get; set; }
    }
    
    [HttpPost]
    public async Task<ActionResult> SaveTest(TxtModel model)