Fixus
Fixus

Reputation: 4641

Cannot get string param in POST method from jQuery

I have POST method like this

    public void PostMethod([FromBody]string param)
    {
        var test = param;
    }

And simple JS script

<script type="text/javascript">
$.ajax({
    url: 'http://localhost:8101/sd/Localization/PostMethod',
    type: 'POST',
    data: {
        param: 'test'
    }
});
</script>

Ot work great. Ajax call is invoking the method BUT the param is null :/ always. I don`t know why. I can't get it running. Can someone pls help me and show me the correct direction ?

// update

too check something i`ve created new project to be sure that i didn't break something. Even in new project in default config I always get null

Upvotes: 0

Views: 135

Answers (1)

cuongle
cuongle

Reputation: 75306

Because param is a simple type, so to make it work for simple type, you just:

<script type="text/javascript"> 
$.ajax({ 
    url: 'http://localhost:8101/sd/Localization/PostMethod', 
    type: 'POST', 
    data:  {"" : 'test' } 
    } 
}); 
</script>

If you still want to make POST request like yours, define you own strong type model:

class YourModel
{
    public string Param {get; set;}
}

So your action:

public void PostMethod(YourModel param)   
{   
    var test = param;   
}

Or use JObject:

public void PostMethod(JObject param)   
{   
    var test = param;   
}

More information:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

Upvotes: 2

Related Questions