I'm making the following AJAX call to an action method in an ASP.NET MVC controller:
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: appControllerUrl + "/SaveAppDetails",
data: {appDetails: JSON.stringify(appDetailsView.model)},
processData: true,
dataType: "json"
});
However I get an HTTP 500 error stating 'No parameterless constructor defined for this object'. Here is my controller:
public class AppDetailsController
{
// GET: AppDetails
AppDetailsController() { }
[HttpPost]
public ActionResult SaveAppDetails(string appDetails)
{
...
}
The 'data' that the Ajax call passes to the controller looks this this:
appDetails= {"id":{"type":"string"},"appName":{"type":"string"},"guid":21}
... so it looks like the actual data I need isn't being passed, however the data string itself seems to be well formed. What's causing the error?
Solutions1
The error means that MVC is trying to instantiate a controller but cannot do so. In C#, if you declare a constructor and don't specify an accessibility modifier, it will be private. You should add the public modifier to the constructor of AppDetailsController.
Talk1:
: no problem, make sure you mark this answer as accepted :)
Solutions2
Javascript Example
appDetailsView.model = {
Id: $.trim(idExample),
AppName: $.trim(appNameExample),
Guid: 21
};
Ajax
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: appControllerUrl + "/SaveAppDetails",
data: JSON.stringify(appDetailsView.model),
processData: true,
dataType: "json"
});
Action
public class AppDetailsController
{
// GET: AppDetails
public AppDetailsController() { }
[HttpPost]
public ActionResult SaveAppDetails(AppDetailsView appDetails)
{
...
}
Class View Model
public class AppDetailsView{
public string Id { get; set; }
public string AppName { get; set; }
public int Guid { get; set; }
}