ajax调用就没有参数,Ajax调用MVC操作方法-没有为此对象定义无参数构造函数

博客讲述了在使用jQuery AJAX进行POST请求到ASP.NET MVC控制器时遇到的一个HTTP500错误。错误信息提示没有找到无参数构造函数。解决方案包括检查控制器的构造函数是否为公共访问,并确保传递的数据格式正确,例如使用模型绑定来接收数据。此外,还提供了一个修正后的JS代码示例和对应的C#控制器代码。
摘要由CSDN通过智能技术生成

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; }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值