In this article I will show you to pass parameter to an angularJS controller using angularJS method ng-init. If the user passes the value via ng-init into an html page and you will get the parameter from the scope object of angularJS controller.
MVC View:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="~/Scripts/app.js"></script>
<div data-ng-app="myModule">
<div data-ng-controller="myController" data-ng-init="init(@Model.UserId)">
<h2>Name of the employee is {{name}}</h2>
</div>
</div>
AngularJS app.js:
angular.module('myModule', []);
function myController($compile, $scope, $http) {
//Thisfunction is sort of private constructor for controller
$scope.init = function (id) {
$scope.myInterval = 5000;
$scope.name = null;
$scope.UserId = id;
$http({
method: 'Get',
url: '/Home/GetData',
params: {
UserId: $scope.UserId
},
}).success(function (data, status,headers, config) {
$scope.name = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
MVC Controller:
public JsonResult GetData(int UserId)
{
using (models context = new models())
{
var ret = context.Users.Where(s => s.UserId == UserId).ToList().Select(x=> new { x.UserId,x.Name }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
The MVC controller receives the parameter UserId and filters the record from the Collection (Users) and return as JSON string and bind to the html element.
Output:
Post your comments / questions
Recent Article
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
Related Article