This has been asked before by others, but I have not been able to use their answers.
I am trying to sending some data by doing the following:
function addForumPost() {
var title = jQuery('#forumTitle').val();
var message = htmlEncode(jQuery('#message').htmlarea("toHtmlString"));
var tagNames = addTags();
var dataPost = $.toJSON({ title: 'testingsadf', message: message, tagNames: tagNames });
jQuery.ajax({
type: "POST",
url: "/Create",
data: dataPost,
dataType: "json",
success: function (result) {
}
});
}
I have checked, and doubled checked that the input contains data, but I only receive the data from the message parameter in my controller. The other two values are null. As you can see in the the example above, I have even assigned some static text to the title parameter, but I still only receive data for the message parameter.
The controller looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string title, string message, List<string> tagNames)
{
....
}
Your error is very simple. If you have an action which returns
JsonResultthen it means not that you have to send also JSON encoded input parameters to the method. Just remove the usage of$.toJSON()and use the object as a value ofdataparameter ofjQuery.ajax(see the answer of Darin for example).If you call ASMX Web Service instead of ASP.NET MVC action you have to use
contentType: "application/json; charset=utf-8"and convert the values of all web-method parameters to JSON but in a little other way (see How do I build a JSON object to send to an AJAX WebService?). But ASP.NET MVC hat no such requirement. MVC converts the input parameters which you send with respect ofParsemethod (int.Parse,DateTime.Parseand so on) and not deserialize from JSON. So if you search for code examples look exactly which technology are used on the backend: ASP.NET MVC, ASMX web serveces or WFC.