[RESOLVED]Post Error, “Error converting value 'ID' to type” to

I changed a relationship between my Job and CustomerEmployee Class, I am trying to make a Post and I am getting a error. Using a break point I see that the Id’s are not making it back to the apiController. I have done some searching and I think it seems
it might be a Json issue, not sure how to correct it. I have 6 Id’s I am trying to Post but they are setup the same so I will show code for one of them

Error Message

$id: "1"
Message: "The request is invalid."
ModelState: {$id:2, newJob.CustomerEmployeePMId:[,…], newJob.CustomerEmployeeAdminId:[,…],…}
$id: "2"
newJob.CustomerEmployeeAccountantId: [,…]
0: "Error converting value 10 to type 'TexasExteriorSPA.Models.CustomerEmployee'. Path    'CustomerEmployeeAccountantId', line 1, position 150."
newJob.CustomerEmployeeAdminId: [,…]
newJob.CustomerEmployeePMId: [,…]
newJob.CustomerEmployeeSuperintendentId: [,…]

view

<select class="form-control" ng-options="customer.CustomerEmployeeId as customer.CustomerEmployeeFirstName + ' ' + customer.CustomerEmployeeLastName for customer in customerEmployeeArray | filter:{CustomerEmployeeRole : 'Accountant', CustomerId : currentItem.CustomerId}  " ng-model="currentItem.CustomerEmployeeAccountantId">
     <option value="" selected="selected">Customer Acct</option>
</select>

Angular Controller

//Post New Job
$scope.submitJob = function () {
    var data = {
        JobId: $scope.JobId,
        CustomerEmployeeAdminId: $scope.currentItem.CustomerEmployeeAdminId
    }
    $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
        console.log(data);
                 $scope.openNewJobModal.then(function (m) {
                   m.modal('hide');
                 });
    });
};

WebApiConfig

// Web API configuration and services
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
           name: "JobApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { controller = "apiJob", id = RouteParameter.Optional }
       );

apiController

 // POST api/<controller>
    public async Task<IHttpActionResult> PostnewJob([FromBody]JobViewModel newJob)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        using (var context = new ApplicationDbContext())
        {
            var job = new Job();

            Mapper.CreateMap<JobViewModel, Job>();
            Mapper.Map(newJob, job);

            context.Jobs.Add(job);

            await context.SaveChangesAsync();

            return CreatedAtRoute("JobApi", new { job.JobId }, job);
        }
    }

Job Class

 public class Job
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Int64 JobId { get; set; }
    public CustomerEmployee CustomerEmployeeAccountantId { get; set; }
}

CustomerEmployee Class

public class CustomerEmployee
{
    [Key]
    public int CustomerEmployeeId { get; set; }
    public string CustomerEmployeeFirstName { get; set; }
    public string CustomerEmployeeLastName { get; set; }
    public string CustomerEmployeeRole { get; set; }

    public Int64? CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

}

It has been suggested that I change the CustomerEmployee CustomerEmployeeAccountantId to int CustomerEmployeeAccountantId but I cannot do that as that is the relationship between those classes. I believe the other route to take is deserializing  JSON but
I am not sure how to do that here. 

First of all you the route you have added for jobapi is of no use. You can not have 2 routes with same
routeTemplate. As it will not make any difference. And try changing you ajax call like

$scope.submitJob = function () {
    var newJob =
{
JobId: $scope.JobId,
CustomerEmployeeAdminId: $scope.currentItem.CustomerEmployeeAdminId
}
var data = JSON.stringify(newJob);
    $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
        console.log(data);
                 $scope.openNewJobModal.then(function (m) {
                   m.modal('hide');
                 });
    });
};

Leave a Reply