不从ajax调用MVC控制器方法

时间:2015-10-08 12:57:08

标签: javascript c# jquery ajax asp.net-mvc

MVC控制器方法没有从我声明的ajax中调用。 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");
    }
});

3 个答案:

答案 0 :(得分:1)

试试这个:

$.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");
}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

  1. 正确构建网址:

    $。AJAX({ 类型:'POST', cache:false, url:' @ Url.AbsoluteAction(“PhoenixInbox”,“Checkfunction”)',

  2. 确保您允许上传获取操作: JsonRequestBehavior.AllowGet

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