简体   繁体   中英

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

    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

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

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

TempData["DCFormList"] can not get value in your AJAX call.

And also check your url in route with url in ajax call.

If I get your question correctly and, and if you want to use ActionResult set result as Success with:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM