简体   繁体   English

从控制器获取结果但 ajax 调用获取错误而不是在 MVC5 和 C# 中成功

[英]Getting the result from controller but ajax call fetching error instead of success in MVC5 and C#

The controller is giving me the result and TempData["DCFormList"] is showing the count 3 (key, value and success message) but in the AJAX call I am getting alert("fail") .控制器给我结果, 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; }
    }
}

I have just tried to reproduce your case.我刚刚试图重现你的情况。 Here are sample code.这里是示例代码。 You can update your code to get from Database from my code.您可以更新您的代码以从我的代码中获取数据库。

Your controller:您的控制器:

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

I create a test in HomeController:Index with Index.cshtml我在 HomeController:Index 中使用 Index.cshtml 创建了一个测试

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

You should use this你应该用这个

Change ActionResult to JsonResult andActionResult更改为JsonResult

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

TempData["DCFormList"] can not get value in your AJAX call. TempData["DCFormList"]无法在您的 AJAX 调用中获取值。

And also check your url in route with url in ajax call.并且还使用 ajax 调用中的 url 检查路由中的 url。

If I get your question correctly and, and if you want to use ActionResult set result as Success with:如果我正确回答了您的问题,并且您想使用 ActionResult 将结果设置为 Success :

Response.StatusCode = (int)HttpStatusCode.OK;

So in your case:所以在你的情况下:

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");

}

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有从ajax调用控制器获取数据作为MVC中的数组数据c# - Not getting data from ajax call to controller as array data in MVC c# 如何使用甜蜜警报发布到控制器动作结果方法? MVC5 C# - How to post to an controller action result method using sweet alert? mvc5 c# 不通过C#控制器操作返回AJAX成功 - Not Returning To AJAX Success From C# Controller Action MVC:在Ajax调用中从控制器返回时,结果不确定 - MVC: When returning from the controller on Ajax call, the result is undefined 将HTML通过AJAX调用传递给C#MVC控制器。 500错误 - Passing HTML over AJAX call to C# MVC Controller. 500 Error MVC C#从ajax调用非控制器方法(帮助器)。 有可能吗? - MVC C# call non controller method (helper) from ajax. Possible or not? 如何在 c#asp.net mvc 中从控制器获取会话变量值到 ajax 调用 - How to fetch Session variable value from a controller to ajax call in c# asp.net mvc 如何在C#MVC5控制器中从没有headerID的Razor页面使用JSon对象 - how to consume JSon object from a Razor page that has no headerID's in C# MVC5 Controller 通过ajax发送文件到另一个动作mvc5 c# - send file through ajax to another action mvc5 c# 获取IEnumerable错误:CS1061不包含C#ASP.NET MVC5 - Getting IEnumerable Error: CS1061 does not contain C# ASP.NET MVC5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM