JQuery Ajax POST字符串参数在MVC Action方法中获取为null的问题排查
Hey, I’ve been in your exact spot before—spending hours trying to figure out why an MVC action keeps getting null parameters even after trying all the usual fixes like JSON.stringify. Super frustrating when you think it should be straightforward! Let’s go through the most common reasons this happens, especially since adjusting the URL makes it work:
Mismatched Parameter Names
Double-check that the parameter name in your jQuery call matches exactly what’s in your MVC Action method. MVC uses name-based binding, so even a tiny difference (likeuserIdvsuserid, or camelCase vs PascalCase) will break it. For example, if your action haspublic ActionResult SubmitData(string orderId), your AJAX data needs to includeorderId: yourValue, not a misspelled variant.Incorrect Content-Type Header
If you’re usingJSON.stringifyto send data, you must set thecontentTypeto"application/json"in your jQuery AJAX setup. Without this, MVC won’t parse the JSON payload correctly, leading to nulls. Here’s a quick example of the right setup:$.ajax({ url: '/Orders/SubmitData', type: 'POST', contentType: 'application/json', data: JSON.stringify({ orderId: '12345' }), success: function(response) { // Handle response } });If you’re sending form data instead of JSON, leave out the
contentType(jQuery defaults to the correct form-encoded type automatically).Route Configuration Conflicts
Since modifying the URL fixes the issue, your route setup is probably conflicting with your parameter. Check your route definitions (either inRouteConfig.csor via attribute routes on your action) to make sure the URL pattern matches what you’re sending. For example, if your route expects a required{id}segment but you’re appending a query string parameter that overlaps, MVC might be trying to bind the wrong value.Query String Encoding Issues
If you’re passing parameters via the URL query string (instead of the POST body), special characters (spaces,&,?, etc.) might not be encoded properly. UseencodeURIComponent()on your parameter values to ensure they’re URL-safe:var orderId = 'ORD-123 & 456'; var url = '/Orders/SubmitData?orderId=' + encodeURIComponent(orderId);Complex Model Binding Gotchas
If you’re sending a complex object instead of a simple string/number, make sure your model has a parameterless constructor (MVC needs this to create an instance) and that all nested property names match exactly what’s in your JSON.
If you can share snippets of your actual jQuery code and MVC Action method, we can pinpoint the exact issue even faster!
内容的提问来源于stack exchange,提问作者Xiao Han

