【问题标题】:Getting the result from controller but ajax call fetching error instead of success in MVC5 and C#从控制器获取结果,但在 MVC5 和 C# 中,ajax 调用获取错误而不是成功
【发布时间】:2019-07-16 11:42:09
【问题描述】:

控制器给我结果,TempData["DCFormList"] 显示计数3(键、值和成功消息),但在 AJAX 调用中我得到alert("fail")

    public ActionResult INTImportData()
    {
        if (Session["UserLogon"] != null)
        {
            BLINTForms objForm = new BLINTForms();
            objDCFormList = new DCFormList();
            int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
            ViewBag.jobId = jobId;
            objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
            TempData["DCFormList"] = objDCFormList.Form;
            return View(objDCFormList.Form);
        }
        else
            return Redirect("~/Account/Login");

    }


function GetINTFormTempData(JobId) {        
    var result = null;
    $.ajax({
        type: "GET",
        url: '/ImportForms/GetINTFormTempDataByJobId',
        data: { jobId: JobId },            
        traditional: false,
        success: function (data) 
            {
                result = data;    
                alert ("JobId");
                LoadINTData(result);               
                if (result.length > 0)
                    $(".upload").show();
                else
                    $(".upload").hide();
            },
        error: function (data) 
        {
            alert("fail");              
            Success = false;
        }

    });


    public List<DCForm> GetINTFormTempDataByJobId(int jobId)
    {
        objDatabaseHelper = new DatabaseHelper();
        List<DCForm> objDCFormList = new List<DCForm>();
        DCForm objDCForm;
        int record = 0;
        try
        {
            objDatabaseHelper.AddParameter("Job_ID", jobId == 0 ? DBNull.Value : (object)jobId);
            DbDataReader reader = objDatabaseHelper.ExecuteReader(BLDBRoutines.SP_GETINTFORMTEMPDATA, CommandType.StoredProcedure);
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    objDCForm = new DCForm();
                    objDCForm.SerialNo = ++record;                        
                    objDCForm.PayerId = reader.IsDBNull(reader.GetOrdinal("PayerId")) ? 0 : reader.GetInt32(reader.GetOrdinal("PayerId"));                      
                    objDCFormList.Add(objDCForm);
                }

            }
            return objDCFormList;
        }
        catch (Exception exce)
        {
            throw exce;
        }
        finally
        {
            if (objDatabaseHelper != null)
                objDatabaseHelper.Dispose();
        }
    }

public class DCForm : DataOperationResponse
{
    public int SerialNo { get; set; }
    public int PayerId { get; set; }


public class DCFormList : DataOperationResponse
{
    private List<DCForm> _form = null;

    public DCFormList()
    {
        if (_form == null)
            _form = new List<DCForm>();
    }

    public List<DCForm> Form
    {
        get { return _form; }
        set { _form = value; }
    }
}

【问题讨论】:

  • 首先,请将您的实际代码添加到问题中,而不是图像。其次,如果error 处理程序被击中,那么您的服务器端代码将失败并且实际上没有返回任何数据。我建议在其中放置一个断点并逐步调试。第三,删除async: false。这是非常糟糕的做法。

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


【解决方案1】:

我刚刚尝试重现您的案例。这是示例代码。您可以更新您的代码以从我的代码中获取数据库。

你的控制器:

public class ImportFormsController : Controller
    {
        public JsonResult INTImportData(int jobId)
        {
            //if (Session["UserLogon"] != null)
            //{
            BLINTForms objForm = new BLINTForms();
            var objDCFormList = new DCForm.DCFormList();
            //int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
            //ViewBag.jobId = jobId;

            objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
            //TempData["DCFormList"] = objDCFormList.Form;
            //Response.StatusCode = (int)HttpStatusCode.OK;
            return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);
            //}
            //else
            //return Json("Login required", JsonRequestBehavior.AllowGet);

        }

    }

    public class BLINTForms
    {
        public List<DCForm> GetINTFormTempDataByJobId(int jobId)
        {

            List<DCForm> objDCFormList = new List<DCForm>();
            DCForm objDCForm;
            int record = 0;
            try
            {
                for (var i = 0; i < 5; i++)
                {
                    objDCForm = new DCForm();
                    objDCForm.SerialNo = ++record;
                    objDCForm.PayerId = 100;
                    objDCFormList.Add(objDCForm);
                }


                return objDCFormList;
            }
            catch (Exception exce)
            {
                throw exce;
            }
            finally
            {

            }
        }
    }

    public class DCForm : DataOperationResponse
    {
        public int SerialNo { get; set; }
        public int PayerId { get; set; }


        public class DCFormList : DataOperationResponse
        {
            private List<DCForm> _form = null;

            public DCFormList()
            {
                if (_form == null)
                    _form = new List<DCForm>();
            }

            public List<DCForm> Form
            {
                get { return _form; }
                set { _form = value; }
            }
        }
    }

    public class DataOperationResponse
    {
        //public string Message { get; set; }
    }

我用 Index.cshtml 在 HomeController:Index 中创建一个测试

<input type="text" id="jobId"/>

<button onclick="GetINTFormTempData($('#jobId').val())">Get Data</button>

<script>

    function GetINTFormTempData(JobId) {
        var result = null;
        $.ajax({
            type: "GET",
            url: '/ImportForms/INTImportData', //**change url**
            data: { jobId: JobId },
            traditional: false,
            success: function(data) {
                result = data;
                alert("JobId");
                alert(JSON.stringify(data));
                LoadINTData(result);
                if (result.length > 0)
                    $(".upload").show();
                else
                    $(".upload").hide();
            },
            error: function(data) {
                alert("fail");
                Success = false;
            }

        });
    }
</script>

【讨论】:

  • 谢谢 Hien Nguyen,返回 Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);这对我有用
【解决方案2】:

你应该使用这个

ActionResult 更改为JsonResult

return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet); 

TempData["DCFormList"] 无法在您的 AJAX 调用中获得价值。

并且还使用 ajax 调用中的 url 检查路由中的 url。

【讨论】:

  • 供将来参考:如果问题离题(在这种情况下它缺少minimal reproducible example),请不要浪费时间回答它,该问题很可能会被关闭并放弃跨度>
  • 是的,我试过但没有工作,但除了这个之外,其他同类的 ajax 调用工作正常
  • 你调试过动作代码吗?如果它没有采取行动,您的网址可能不正确
  • return Json(objDCFormList.Form, JsonRequestBehavior.AllowGet);我尝试了这个并获取 json 数据,但我需要在网格中显示该数据。其实我需要返回视图
  • 你能同时发布 BLINTForms、DCFormList 和 AJAX 的 javascript 代码吗
【解决方案3】:

如果我正确地回答了您的问题,并且如果您想使用 ActionResult 集结果为 Success with:

Response.StatusCode = (int)HttpStatusCode.OK;

所以在你的情况下:

public ActionResult INTImportData()
{
    if (Session["UserLogon"] != null)
    {
        BLINTForms objForm = new BLINTForms();
        objDCFormList = new DCFormList();
        int jobId = Session["Job_ID"] == null ? 0 : (int)Session["Job_ID"];
        ViewBag.jobId = jobId;
        objDCFormList.Form = objForm.GetINTFormTempDataByJobId(jobId);
        TempData["DCFormList"] = objDCFormList.Form;
        Response.StatusCode = (int)HttpStatusCode.OK;
        return View(objDCFormList.Form);
    }
    else
        return Redirect("~/Account/Login");

}

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2011-02-06
    相关资源
    最近更新 更多