0

I built a sample MVC application in which I tried to implement functionality to insert a record using angular js.

Here is the index cshtml page.

@{
    ViewBag.Title = "Add User";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section adduser 
{
    @*Index.html*@
    <div class="container-fluid" ng-app='MyData' ng-controller='DataController'>
        <table class="table table-striped table-bordered table-responsive">
            <tr>
                <td>
                    <label class="text-primary">User Name:</label>
                </td>
                <td>
                    <input type="text" id="txtUserName" class="text-primary" required="required" ng-model="newUser" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" id="btnSubmit" class="btn btn-success" ng-click="AddUser()" />
                </td>
            </tr>
        </table>
    </div>
}

Here is the Model js code

var myData = angular.module('MyData', []);

Here is the controller JS code

myData.controller("DataController", function($scope) {
    $scope.newUser = "";
    $scope.addUser = function() {
        $http.post("/Home/AddUser/", { newUser: $scope.newUser }).success(function (result) {
            alert(result.success);
        }).error(function(data) {
            console.log(data);
        });
    };
});

Here is the post method inside controller which i am calling through angular js

[HttpPost]
        public JsonResult AddUser(string name)
        {
            var db = new SchedulerEntities();
            db.Users.Add(new User {Name = name});
            db.SaveChanges();
            return null;
        }

I am adding an entry into DB from controller method but nothing is happening...

2
  • Can you show us the error you get ?? Is the value received in AddUser method correctly ? Commented Aug 6, 2015 at 11:12
  • I am not able to get error info as well because debugger is not pointing at the line of code. Commented Aug 6, 2015 at 11:48

1 Answer 1

3

I think you need to declare $http in the function:

myData.controller("DataController", function($scope, $http) {
    $scope.newUser = "";
    $scope.addUser = function() {
        $http.post("/Home/AddUser/", { newUser: $scope.newUser })
        .success(function (result) {
            alert(result.success);
        }).error(function(data) {
            console.log(data);
        });
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

this would work for you @rsn. But I would suggestion you to use angular services to post data and use that services in your controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.