Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using webapi and angularjs in my ASP.net MVC app. Everything is working good but in my insert (post) method I need to check if a value exists in the db before doing an insert. I am not sure where that should go. I ruled out the webapi because a void does not return a value. The logical place seems to be the controller, but I cannot find the right way to call my angular getEmployee(id) method from within the insert controller method. Any help is appreciated.

Angular controller (post):

$scope.insertEmployee = function (employee) {
    employeeFactory.insertEmployee(employee)
        .success(function (emp) {
            $scope.employee = emp;
        })
        .error(function (error) {
            $scope.status = 'Unable to load employee data: ' + error.message;
        });
};

Angular factory (post):

factory.insertEmployee = function (employee) {
    url = baseAddress + "employee/insert/";
    $http.post(url, employee).success(function (data) {
        alert("Saved Successfully!!");
    }).error(function (data) {
        $scope.error = "An Error has occured while saving employee! " + data;
    });
};

webapi controller post method:

    [Route("api/employee/insert/")]
    public void Post(Employee employee)
    {
        if (ModelState.IsValid)
        {
            context.Employee.Add(employee);
            context.SaveChanges();
        }
    }

Angular controller (get):

$scope.getEmployees = function (term) {
    employeeFactory.getEmployees(term)
        .success(function (data) {
            $scope.employees = data;
        })
        .error(function (error) {
            $scope.status = 'Unable to load employee data: ' + error.message;
        });
};
share|improve this question
    
how come '$scope' is inside 'insertEmployee'? –  Ben Diamant Feb 10 at 19:11
    
I don't know. It is an example I found on the internet. noob with angular –  steveareeno Feb 11 at 16:59

3 Answers 3

up vote 1 down vote accepted

I would suggest doing this in your web-api server side. You can construct an exception and throw it. Some pseudo-code:

   [Route("api/employee/insert/")]
    public void Post(Employee employee)
    {
        if (ModelState.IsValid)
        {
            // verify doesn't already exist
            if(...item-already-exists...) {
               var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
               {
                  Content = new StringContent("Employee already exists!")),
                  ReasonPhrase = "Employee already exists!"
               }
               throw new HttpResponseException(resp);
            }

            context.Employee.Add(employee);
            context.SaveChanges();
        }
    }
share|improve this answer
    
Thanks. this is what I thought but having two controllers (MVC and Angular) threw me for a loop, especially since webapi controller methods don't have return values –  steveareeno Feb 11 at 17:04

Your factory doesn't match your controller. If you want to use success and error from employeeFactory.insertEmployee, it needs to return the promise:

factory.insertEmployee = function (employee) {
  url = baseAddress + "employee/insert/";
  return $http.post(url, employee);
};

So then you can do

employeeFactory.insertEmployee(employee).success( ... )

Now to answer your question you could either do a database read in insertEmployee to check if the value exists before you insert it. Or save a server call and do the check during the insert request: if the employee exists, return an error or a specific message to tell the client.

share|improve this answer
    
Thanks. I will make the adjustment. –  steveareeno Feb 11 at 17:00

With the help of floribon and Nicholas Smith I managed to come up with a solution that bubbles the error up to my view, which I display in a div element. This is only bare bones, but is a start.

My angular controller:

$scope.insertEmployee = function (employee) {
    employeeFactory.insertEmployee(employee)
        .success(function (data) {
            $scope.employee = data;
            $scope.status = 'The item was saved';
        })
        .error(function (error) {
            $scope.status = 'Unable to save the employee data: ' + error;
        });
};

My angular factory:

factory.insertEmployee = function (employee) {
    url = baseAddress + "employee/insert/";
    return $http.post(url, employee);
};

my webapi controller:

    [Route("api/employee/insert/")]
    public HttpResponseMessage Post(Employee employee)
    {
        HttpResponseMessage response;

        // check for the employee
        var employeeCheck = context.Employee
                        .Where(b => b.EmployeeNumber == employee.EmployeeNumber)
                        .FirstOrDefault();

        if (employeeCheck == null)
        {
            // save the item here
            response = Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
        }
        return response;
    }

The result is the message is "Unable to save the employee data: The item already exists".

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.