Home > other >  Can't fetch the data in MVC by ajax
Can't fetch the data in MVC by ajax

Time:09-16

I want to fetch data from a database in ASP.NET MVC with Ajax.

This is my controller:

public JsonResult EditCustomer(int Id)
{
        Customer customer = new Customer();

        if (Request.IsAjaxRequest())
        { 
            using (SEntities dc = new SEntities())
            { 
                customer = dc.Customers.Where(a => a.ID == Id).SingleOrDefault();
                customer.Events = null;
            }
        }

        return Json(customer, JsonRequestBehavior.AllowGet);
}

and this is the Ajax in the view

var EditCustomer = function (Id) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '/BasicInfo/EditCustomer',
        data: { 'Id': Id },
        success: function (data) {
            $('#txtFirstName').val(data.FirstName);
            $('#txtLastName').val(data.LastName);
            $('#txtPhone').val(data.Phone);
            $('#txtID').val(data.ID);
            $('#hdUserID').val(data.UserId);
            $('#txtNote').val(data.ClientNote);
            $("#myModalEdit").modal("show");

        },
        error: function () {
            alert('Failed EditCustomer');
        }
    })
}

Although the variable customer from controller is correctly populated but in the view I just get the error "Failed EditCustomer".

What could cause this problem?

CodePudding user response:

I solved it just by adding

 dc.Configuration.LazyLoadingEnabled = false;

before fetching data in controller. and it worked.

  • Related