Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posted values to MVC6 controller are null

I am porting my web application from MVC5 to MVC6. This function used to work fine in MVC5 but not in MVC6.

I am posting data, via AngularJS, to this WebAPI method but the search parameter is always null. Ive tried decorating it with [FromBody] and [FromHeader] but neither seem to work. The controller gets hit, the value is just null, what is wrong?

[HttpPost("AdvancedSearch")]
public List<MatchResult> AdvancedSearch(string searchParameter)
{
    var searchResults = service.GetResults(searchParameter);

    return searchResults;
}

My AngularJS call looks like this

myAPI.advancedSearch = function (searchParameter) {
    var url = '/api/advancedsearch/';

    // Request data
    return $http({
        method: 'POST',
        data: { searchParameter: searchParameter },
        url: url
    });
}

I verified that the data is sent, in Chrome webtools the "Request Payload" is correct

{searchParameter: "n1"}
like image 660
Chris Avatar asked Dec 13 '25 02:12

Chris


2 Answers

I found a way to do this without using a model or querystring. This answer explains it but essentially you can use

[HttpPost]
public System.Net.Http.HttpResponseMessage Post([FromBody]dynamic value)
{
   //...
}

value will then contains all your post data.

Edit

For further reading please see this post, including a table of all the binding situations and when it will and won't work!

like image 195
Chris Avatar answered Dec 15 '25 15:12

Chris


If you think an object is overkilling, you can always use querystrings. I know, looks "old", but it's still working I guess.

 myAPI.advancedSearch = function (searchParameter) {
    var url = '/api/advancedsearch?searchParameter=' + searchParameter ;

    // Request data
    return $http({
        method: 'POST',
        data: { },
        url: url
    });
 }

[HttpPost("AdvancedSearch")]
public List<MatchResult> AdvancedSearch([FromQuery]string searchParameter)
{
    var searchResults = service.GetResults(searchParameter);

    return searchResults;
}
like image 23
Luca Ghersi Avatar answered Dec 15 '25 14:12

Luca Ghersi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!