没有从ajax调用MVC控制器方法

本文关键字:MVC 控制器 方法 调用 ajax | 更新日期: 2023-09-27 18:16:56

没有从我声明的ajax调用MVC控制器方法。PFB代码片段c#控制器:

public ActionResult Checkfunction(string ReqID, string AssociateId, string AssetId)
{
      MyDetails obj = new MyDetails();
      List<string> Lst = new List<string>();
      Lst = obj.Check(AssociateId, AssetId, ReqID);
      return this.Json(Lst, "text/json");
}

Javascript代码(ajax调用):引用细节控制器和webmethod Checkfunction

$.ajax({
    type: 'GET',
    cache: false,
    url: '@Url.Action("Details/Checkfunction")',
    data: { 'ReqID': RequestId, 'AssociateId': AssociateID, 'AssetId': Host_Name },
    contentType: "application/json",
    success: function (data) {
        debugger;
        if (data.length > 0) {
                ViewModel.REQUESTID() = data[0];
                ViewModel.FLAG() = '1';
        }
        else {
            debugger;
            ViewModel.FLAG() = '0';
            ViewModel.REQUESTID() = '';
        }
        if (ViewModel.REQUESTID() != '' || ViewModel.REQUESTID() != null) {
            debugger;
            ViewModel.REQID() = RequestId;
        }
    },
    error: function (error) {
        alert("error");
    }
});

没有从ajax调用MVC控制器方法

试试这个:

$.ajax({
type: 'POST',
cache: false,
url: '/PhoenixInbox/Checkfunction',
data: { 'ReqID': RequestId, 'AssociateId': AssociateID, 'AssetId': Host_Name },
contentType: "application/json",
success: function (data) {
    debugger;
    if (data.length > 0) {
            ViewModel.REQUESTID() = data[0];
            ViewModel.FLAG() = '1';
    }
    else {
        debugger;
        ViewModel.FLAG() = '0';
        ViewModel.REQUESTID() = '';
    }
    if (ViewModel.REQUESTID() != '' || ViewModel.REQUESTID() != null) {
        debugger;
        ViewModel.REQID() = RequestId;
    }
},
error: function (error) {
    alert(JSON.stringify(error));
}
});

控制器:

[Httppost]
public ActionResult Checkfunction(string ReqID, string AssociateId, string AssetId)
{
      MyDetails obj = new MyDetails();
      List<string> Lst = new List<string>();
      Lst = objMyAssetsDetails.Check(AssociateId, AssetId, ReqID);
      return this.Json(Lst, "text/json");
}

现在最好使用promise,如果你要返回json,最好返回JsonResult而不是ActionResult

http://davidwalsh.name/write-javascript-promises

  1. 正确构建url:

    . ajax({美元类型:"文章",缓存:假的,url: ' 。AbsoluteAction("PhoenixInbox"、"Checkfunction"),

  2. 确保允许get on get action: JsonRequestBehavior。AllowGet

    public ActionResult Checkfunction(string ReqID, string AssociateId, string AssetId){MyDetails obj = new MyDetails();List List = new List();Lst = objMyAssetsDetails。Check(AssociateId, AssetId, ReqID);返回。Json(Lst, "text/Json ", JsonRequestBehavior。AllowGet);}