Get information from database with ajax ASP.NET

I'm trying to get some information from a table in my database whenever a select-field changes.

I'm able to do the response and the Ajax jQuery function return success(function)
The problem is i don't know how to return the data from my database using ASP.net MVC.
The response i'm getting from my Ajax call on success is this text:

ProduktWebKort.Models.WarehouseCustomer[]

This is the part of my controller with the function called via Ajax

[HttpPost]
public string OnChange(int id)
{
    return db.Customers.Where(C => C.CustomerID == id).ToString();
}

My Ajax call looks like this:

<script type="text/javascript">
$(function () {
    // Document.ready -> link up remove event handler
    $("#CustomerID").change(function () {
        alert("Hej");
        var option = $('option:selected', this).val();
        $.ajax({
            type: "POST",
            url: '@Url.Action("Index/1", "Session")',
            contentType: "application/json; charset=utf-8",
            data: { id: 1 },
            dataType: "html",
            success: function (success) {
                alert('Success');
                console.log(success);
                for (var i = 0; i < success.length; i++) {
                    $(".form-horizontal").append("<li>" + success[i] + "      </li>");
                    console.log(success);
                }
            },
            error: function (e, text, string) {
                alert(e.message + text + string);
                console.log(e);
            }
        });
    });
});
</script>

I want to return every entry from WarehouseCustomer with the CustomerID of id from my select field.

Upvotes: 1

Views: 2531

Answers (3)

teo van kot
teo van kot

Reputation: 12491

Your problem on both server and client side. If you want to get List of customers on server side you should write your Controller like this:

[HttpPost]
public JsonResult OnChange(int id)
{
    return Json(db.Customers.Where(C => C.CustomerID == id).ToList());
}

On client side you should change your ajax code like this if you want to work with IEnumerable result:

     $.ajax({
        type: "POST",
        url: '@Url.Action("OnChange", "Session")',
        data: { id: 1 },
        dataType: "json",
        success: function (success) {
        alert('Success');
        console.log(success);
        $.each(success, function (i, item) {
           $(".form-horizontal").append("<li>" + item.CustomerID  + "</li>");                                              
           }); 
        },
        error: function (e, text, string) {
            alert(e.message + text + string);
            console.log(e);
        }
    });

I hope your OnChange method is in Session Controller. You can access other properties of your list elements like this (item.CustomerID), as you understand.

Upvotes: 0

mason
mason

Reputation: 32694

In an MVC 5 project, you use Web API to respond to AJAX requests. Web API examines the request for what is being requested and what format the client supports. It then serializes to JSON or XML or other formats appropriately. It also follows the MVC architecture closely, and has been merged into the MVC framework as of the upcoming MVC 6.

Install Web API in your project via NuGet. Enable attribute routing.

[RoutePrefix("api/customers")]
public class CustomerController : ApiController
{
    [Route("byid/{id}")]
    public List<Customer> GetCustomers(int id)
    {
        return db.Customers.Where(C=>C.CustomerID==id).ToList();
    }
}

That should return a list of customer objects in the data format requested by the client (by default JSON).

The URL you request should be an HTTP GET request to ~/api/customers/byid/{id}, ex: ~/api/customers/byid/5. I often use the MVC Helper @Url.Content() for mapping to Web API on the client side.

Your success handler should be like this:

success: function (customers) {
            alert('Success');
            console.log(customers);
            for (var i = 0; i < customers.length; i++) {
                $(".form-horizontal").append("<li>" + customers[i].Name + "</li>");
                console.log(success);
            }
        },

Upvotes: 1

VMAtm
VMAtm

Reputation: 28345

The default implementation of the .ToString() method in .NET is returning the type of an object. So the resulting text you've got is exactly what are you dealing with: array of the WarehouseCustomer objects:

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

To get data from your server you should serialize the data object, either in XML or JSON form (preferred variant) to resolve them on the client side.

The ways you can do it are numerous, so you should just select the one you're comfortable with. I suggest you to see after @mason's answer as it looks like the best way to solve your problem.

Upvotes: 1

Related Questions