2

Hey guys I´m having some issues by getting a value to the controller in MVC.

This is my HttpPost at the controller:

[HttpPost]
    public void GlobalIsWeekCheck(bool? incomingIsWeek)
    {
        GlobalIsWeek = incomingIsWeek;
    }

And this is my script on the view:

var incomingIsWeek = false;
$.ajax({
                    type: "POST",
                    url: "/Home/GlobalIsWeekCheck",
                    data: incomingIsWeek,
                    success: function() {
                        alert('Successfully connected to the server');
                    }, 
                    error: function() {
                        alert('Something went wrong');
                    }
                });

Anyone knows why am I getting a null variable on my controller everytime I call this ajax?

Marcelo
  • 784
  • 3
  • 9
  • 30

2 Answers2

3

Your data needs to be an object with the correct name so that it can be assigned to the variable.

Adjust like so

data: {"incomingIsWeek" : incomingIsWeek}
Zach
  • 1,964
  • 2
  • 17
  • 28
0

Your action lacks FromBody, because the input parameter is not a complex object and the action selector try to pick up it parameter from uri.

[HttpPost]
public void GlobalIsWeekCheck([FromBody]bool? incomingIsWeek)
{
    GlobalIsWeek = incomingIsWeek;
}

Here is the official documentation.

By default, Web API uses the following rules to bind parameters:

If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)

For complex types, Web API tries to read the value from the message body, using a media-type formatter.

lucky
  • 12,734
  • 4
  • 24
  • 46
  • It looks like ReSharper issue. https://stackoverflow.com/questions/15713167/resharper-can-not-resolve-symbol-even-when-project-builds – lucky Jan 25 '18 at 19:58
  • I´ve already fixed the issue by using Zachs fix. I do not know if this will work...indeed seems to be something about Resharper. – Marcelo Jan 25 '18 at 20:06
  • `[FromBody]` is web-api (not mvc as the question has been tagged) –  Jan 25 '18 at 20:15