How to pass a javascript object to a C# MVC 4 controller
- Make sure the property names match between the javascript and the C# model. In your question you had
Propr1
andPropr2
for the javascript object, but in the C# model you hadProp1
andProp2
(missing the "r"). - Do not
stringify
the data before sending it, and do not setdataType
tojson
. MVC can parse just fine with a collection of post parameters without the json serialization in your code. - Omit the
contentType
, it is not necessary. WebAPI should autodetect this. You can leave it, but it's extraneous. - Make sure the model properties are public.
Javascript Client side:
var myData = {Prop1: '', Prop2: ''}; // #1 $.ajax({ type: 'POST', data: myData, // #2 url: '/Home/SubmitMyData', //contentType: 'application/json', #3 //dataType: 'json', #2 success: alert('Youhou'), error: alert('not good') });
C# Server side method:
public ActionResult SubmitMyData(MyParamModel myParam) { // Do my stuff here with my parameter return View(); } public class MyParamModel // #4 { public string Prop1 { get; set; } public string Prop2 { get; set; } }
The value you pass for the data
property should be an object, not a string:
data: myData,
the property names need to match:
var myData = { Prop1: '', Prop2: ''};
you need to use the [FromBody]
attribute on your parameter value:
public ActionResult SubmitMyData([FromBody] MyParamModel myParam)
and the properties on your model type need to be public
:
public class MyParamModel{ public string Prop1 { get; set; } public string Prop2 { get; set; }}