Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a controller named CustomersInfoAPIController. I'm using Knock out, webapi2, asp.net mvc5 to build an application. I'm binding the data using knout JS. When I run the application and debug the knockout script, I don't see any error .When I try to insert data using AJAX I see error `"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"

the ajax code is:
Razor
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
@{
    ViewBag.Title = " Add Customer";
}
<script src="~/Scripts/knockout-3.3.0.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
<script type="text/javascript">
var addCustomerViewModel;

// use as register student views view model
function Customer(Id, CustomerName, ContactName, Address, City, PostalCode,Country) {
    var self = this;

    // observable are update elements upon changes, also update on element data changes [two way binding]
    self.Id = ko.observable(Id);
    self.CustomerName = ko.observable(CustomerName);
    self.ContactName = ko.observable(ContactName);
    self.Address = ko.observable(Address);
    self.City = ko.observable(City);
    self.PostalCode = ko.observable(PostalCode);
    self.Country = ko.observable(Country)
    


    self.addCustomer = function () {
        var dataObject = ko.toJSON(this);

        $.ajax({
            url: '/api/CustomersInfo/Post',
            type: 'post',
            data: dataObject,
            contentType: 'application/json',
            success: function (data) {
                addCustomerViewModel.customerListViewModel.customers.push(new Customer(data.Id,data.CustomerName, data.ContactName, data.Address, data.City, data.PostalCode, data.Country));
                self.Id(null);
                self.CustomerName('');
                self.ContactName('');
                self.Address('');
                self.City('');
                self.PostalCode(0);
                self.Country('');
            }
        });
    };
}

// use as customer list view's view model
function CustomersList() {

    var self = this;

    // observable arrays are update binding elements upon array changes
    self.customers = ko.observableArray([]);

    self.getCustomers = function () {
        // retrieve customers list from server side and push each object to model's students list
        self.customers.removeAll();
        $.getJSON('/api/CustomersInfo/Get', function (data) {
            $.each(data, function (key, value) {
                self.customers.push(new Customer(value.Id,value.CustomerName, value.ContactName, value.Address, value.City, value.PostalCode, value.Country));
            });
        });
    };


    // remove customer. current data context object is passed to function automatically.
    //self.removeCustomer = function (customer) {
    //    $.ajax({
    //        url: '/api/CustomersInfo/' + customer.Id(),
    //        type: 'delete',
    //        contentType: 'application/json',
    //        success: function () {
    //            self.customers.remove(customer);
    //        }
    //    });
    //};
}


// create index  view model which contain two models for partial views
customerRegisterViewModel = { addCustomerViewModel: new Customer(), customerListViewModel: new CustomersList() };


// on document ready
$(document).ready(function () {

    // bind view model to referring view
    ko.applyBindings(customerRegisterViewModel);

    // load student data
    customerRegisterViewModel.customerListViewModel.getCustomers();
});
</script>
<div class="page-header">
    <h2 class="text-center">Customer Registration</h2>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="panel panel-info">
            <div class="panel-heading">
                <h2 class="panel-title">Register new Customer</h2>
            </div>

            <div class="panel-body" data-bind="with: addCustomerViewModel">
                @Html.Partial("_InsertCustomer")
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2 class="panel-title">Registerd Customers</h2>
            </div>
            <div class="panel-body" data-bind="with: customerListViewModel">
                @Html.Partial("_DisplayCustomers")
            </div>
        </div>
    </div>

</div>



My Controller action is :

C#
public class CustomersInfoController : ApiController
   {

       // GET api/student
       public IEnumerable<Customer> Get()
       {
           return CustomersRepository.GetCustomers();
       }

       // GET api/student/5
       public Customer Get(int Id)
       {
           return CustomersRepository.GetCustomers().FirstOrDefault(s=>s.ID == Id);
       }

       // POST api/student
       public HttpResponseMessage Post(Customer customer)
       {
           CustomersRepository.InsertCustomer(customer);
           var response = Request.CreateResponse(HttpStatusCode.Created, customer);
           string url = Url.Link("DefaultApi", new { customer.ID });
           response.Headers.Location = new Uri(url);
           return response;
       }

       // DELETE api/student/5
       public HttpResponseMessage Delete(int id)
       {
           CustomersRepository.DeleteCustomer(id);
           var response = Request.CreateResponse(HttpStatusCode.OK, id);
           return response;
       }
   }

How to avoid this error so that I can store the data
Posted
Updated 13-Nov-15 19:56pm
v5
Comments
[no name] 14-Nov-15 0:27am    
What the value you are passing in dataObject variable in your AJAX. Secondly provide controller action details..
We need to verify the object you are sending as well as the controller action.
F-ES Sitecore 14-Nov-15 9:27am    
Use Fiddler to examine the request to see what is sent in the response, you might find an actual error message there.

1 solution

I don't see the method "CustomersInfo" in your controller codes. So, as it is absent, it is giving you a 500 error.
 
Share this answer
 
Comments
Member 11849988 14-Nov-15 1:31am    
<error>
<message>The request is invalid.
<messagedetail>
The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type 'System.Int32' for method 'KnockOutMVCDemo.EntityModel.Customer Get(Int32)' in 'KnockOutMVCDemo.Controllers.CustomersInfoController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.


This is the error I'm getting when I click on the url api/CustomersInfo/POST
url: '/api/CustomersInfo'

Here it should have the method name after the controller name. Like...

url: 'api/ControllerName/MethodName'

Then check the data you are sending, if it matches the data types of the method parameters or not. After that start debugging.
Member 11849988 14-Nov-15 2:19am    
I have updated the code .please check it
I think the data you are sending is wrong. Have you checked by debugging?

var dataObject = ko.toJSON(this);

should be...

var dataObject = ko.toJSON(self);

as self contains all the data.
Member 11849988 14-Nov-15 1:59am    
Tried adding the method name at the end of the url.It's throwing two errors:
1.400 Bad request
2: 500 Internal Server Error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900