Cristoffer Ryrberg
Cristoffer Ryrberg

Reputation: 95

Passing a bool parameter to .NET Core2 MVC Controller with Jquery Ajax

I'm migrating an old asp.net Web forms application to .NET CORE2 MVC and while trying to make an AJAX call to a controller with a bool parameter the controller doesn't seem implicitly parse it to bool as it used to in the ASP solution. When true is passed to the controller the parameter still ends up as false. I know that the parameter is sent correctly. Does .NET Core lack support for this, or am I missing something?

PS. I could change the parameter to JObject and retrieve the value that way, but I'm cursios as to why is isn't working like it is.

Thanks!

AJAX

$.ajax({
            type: "POST",
            url: "GetActiveUsersAndAllGroups",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({ secret: bfsGrupper.secret }),
            beforeSend: ShowLoader(),
            complete: function () { $.unblockUI(); },
            success: function (response) {
                //Stuff
            },
            error: function (response) {
                //Stuff
            }
        });

Controller

    [Route("GetActiveUsersAndAllGroups")]
    public IActionResult GetActiveUsersAndAllGroups([FromBody] bool secret)
    {
        return Ok(_manager.GetBaseTableData(HttpContext.User.Identity.Name,secret));
    }

Upvotes: 0

Views: 3908

Answers (1)

J.P.
J.P.

Reputation: 5753

Model binding most definitely works in ASP.NET Core. It's not working for you because you're trying to get a primitive boolean secret as a parameter, but in your POST you're sending a JSON object. Either change the parameter to accept a class or don't send an entire JSON object.

I also noticed you're sending a POST request to a URL called GetActiveUsersAndAllGroups. I would probably choose to then change the POST request to a GET request as POST is meant for persisting data. The added benefit of this is that you can pass along the secret as a querystring parameter, which feels more appropriate to do in this scenario: GetActiveUsersAndAllGroups?secret=true. Remember to then change the [FromBody] to a [FromQuery].

Upvotes: 2

Related Questions