Ajax调用控制器函数不返回数据

时间:2014-09-18 05:48:28

标签: javascript jquery ajax asp.net-mvc

我有一个MVC 5网页,我需要在我的Controller页面上调用一个函数,从我使用Ajax的视图。我的问题是,即使对函数的Ajax调用有效(函数被调用,并返回我期望的数据),我也无法获得Ajax.Success中返回的值,但是当我调用失败时,我可以在“错误”中获得返回值。

这是我在View中的Ajax调用:

function FindFreeCards() {
$.ajax({
  url: '@Url.Action("FindFreeCards", "AdminCards")',
  contentType: "application/json; charset=utf-8",
  type: 'POST',
  success: function (data) {
    alert('SUCCESS');
    var FreeCards;
    FreeCards = data.d;

    alert(FreeCards);

    $('#lblFreeCards').html(FreeCards);
    $('#modalSelectFreeCard').modal();
  },
  error: function (request, status, error) {
    alert('ERROR');
    alert(request.responseText);
    alert(status.toString());
    alert(error.toString());
  }
});

};

这是我在Controller中的功能:

public string FindFreeCards()
{
  string FreeCards = "";

  using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString))
  {
    con.Open();
    SqlCommand sqlCom;
    SqlDataReader sqlReader;
    System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString);
    Con.Open();
    sqlCom = new SqlCommand("LicensePlateFindFreeCard", con);
    sqlCom.CommandType = CommandType.StoredProcedure;
    sqlCom.Parameters.Add("@CustomerId", SqlDbType.Int).Value = 12;

    sqlReader = sqlCom.ExecuteReader();

    if (sqlReader.HasRows)
    {
      while (sqlReader.Read())
      {
        FreeCards = FreeCards + sqlReader["CardNo"].ToString() + ", ";
      }
    }

    FreeCards = FreeCards.Trim().TrimEnd(',');

    if (FreeCards.Contains(','))
    {
      int LastComma = FreeCards.LastIndexOf(',');
      FreeCards = FreeCards.Remove(LastComma, 1);
      FreeCards = FreeCards.Insert(LastComma, " og");
    }
    sqlReader.Close();
    sqlReader.Dispose();
    sqlCom.Dispose();
    con.Close();
    con.Dispose();
  }
  return FreeCards;
}

控制器函数不带任何参数,这就是我从Ajax调用中省略了“data:”和“dataType:”参数的原因。

当我调用该函数时,成功中的第一个警报用“SUCCESS”一词触发,但第二个警报(我想显示返回值)显示“undefinded”。

如果我将参数“data:”{}“”添加到Ajax调用中,则调用失败并显示警报('ERROR'),然后是警报(request.responseText),实际上此警报包含函数工作时我希望得到的值。

任何建议如何在Ajax调用成功时获取返回值?

3 个答案:

答案 0 :(得分:0)

您需要将json返回为:

public ActionResult FindFreeCards()
{
  string FreeCards = "";

  using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString))
  {
    con.Open();
    SqlCommand sqlCom;
    SqlDataReader sqlReader;
    System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString);
    Con.Open();
    sqlCom = new SqlCommand("LicensePlateFindFreeCard", con);
    sqlCom.CommandType = CommandType.StoredProcedure;
    sqlCom.Parameters.Add("@CustomerId", SqlDbType.Int).Value = 12;

    sqlReader = sqlCom.ExecuteReader();

    if (sqlReader.HasRows)
    {
      while (sqlReader.Read())
      {
        FreeCards = FreeCards + sqlReader["CardNo"].ToString() + ", ";
      }
    }

    FreeCards = FreeCards.Trim().TrimEnd(',');

    if (FreeCards.Contains(','))
    {
      int LastComma = FreeCards.LastIndexOf(',');
      FreeCards = FreeCards.Remove(LastComma, 1);
      FreeCards = FreeCards.Insert(LastComma, " og");
    }
    sqlReader.Close();
    sqlReader.Dispose();
    sqlCom.Dispose();
    con.Close();
    con.Dispose();
  }
  return Json(new {d=FreeCards });
}

答案 1 :(得分:0)

因为你要返回一个字符串这个语句

FreeCards = data.d; 

仅给出undefined ..直接数据将包含结果。尝试将该行转为

FreeCards = data

希望有所帮助

答案 2 :(得分:0)

首先在控制器上使用list返回json,如下所示:

        public ActionResult FindFreeCards()
        {
          List <string> FreeCards = new List<string>();

          using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString))
          {
            con.Open();
            SqlCommand sqlCom;
            SqlDataReader sqlReader;
            System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString);
            Con.Open();
            sqlCom = new SqlCommand("LicensePlateFindFreeCard", con);
            sqlCom.CommandType = CommandType.StoredProcedure;
            sqlCom.Parameters.Add("@CustomerId", SqlDbType.Int).Value = 12;

            sqlReader = sqlCom.ExecuteReader();

            if (sqlReader.HasRows)
            {
              while (sqlReader.Read())
              {
                 FreeCards.add(sqlReader["CardNo"].ToString());
              }
            }


            sqlReader.Close();
            sqlReader.Dispose();
            sqlCom.Dispose();
            con.Close();
            con.Dispose();
          }
          return Json(FreeCards);
        }

然后使用jQuery.parseJSON解析ajax repsone。使用以下代码:

               function FindFreeCards() 
    {
        $.ajax({
          url: '@Url.Action("FindFreeCards", "AdminCards")',
          contentType: "application/json; charset=utf-8",
          type: 'POST',
          success: function (data) {
            /*New code */
            var data=jQuery.parseJSON(data);
             $.each(data, function(i, item) {
                                alert(i + " ==> "+  item );
                    });
            /*New code */
            alert('SUCCESS');

            var FreeCards;
            FreeCards = data.d;

            alert(FreeCards);

            $('#lblFreeCards').html(FreeCards);
            $('#modalSelectFreeCard').modal();
          },
          error: function (request, status, error) {
            alert('ERROR');
            alert(request.responseText);
            alert(status.toString());
            alert(error.toString());
          }
        });
    };