I am trying to navigating from login page to Home page but it is not navigating to login page even though it is hitting HomeController, here i used angularjs http.get service for navigating.
I have verified RouteConfig settings, but am unable to find the problem where it is.
Below is route config
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
angular code
(function () {
var app = angular.module("AngularApp", []);
app.service("loginservice", function ($http) {
this.Checkuser = function (UserName, password) {
return $http({
method: "Post",
url: "Login/LoginUserAuth/",
data: { UserName: UserName, password: password }
});
}
this.NavigateToHome = function (UserName) {
return $http({
method: "get",
url: "Home/Index"
});
}
});
app.controller("LoginController", function ($scope, $http, loginservice) {
$scope.Checkuser = function () {
var checkresult = loginservice.Checkuser($scope.username, $scope.password);
checkresult.success(function (dataFromServer, status, headers, config) {
//alert(dataFromServer);
if (dataFromServer == '"Login Success"') {
var NavigateToHome = loginservice.NavigateToHome($scope.username);
}
else {
alert('Wrong UserName or Password');
}
});
checkresult.error(function () {
alert('Error in Login');
});
}
});
}
())
Home controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
Related
I need to call Initailly the parameterized constructor from the angular js $http url that which maps the action method in MVC .
My angular js controller code is as follows:-
var app = angular.module("ourSiteLogIn", []);
app.controller("ourSiteLogInController", function ($scope, $http) {
$scope.GetLogInByUserIdPassword = function () {
$http({
method: "POST",
url: "User/GetLogInByUserIdPassword",
params: {
UserId: $scope.UserId,
Password: $scope.Password
}
}).then(function mySuccess(response) {
$scope.User = response.data;
}, function myError(reason) {
$scope.error = reason.data;
});
};
});
below is my controller :
public class UserController : Controller
{
private readonly ILogIn _login;
private readonly IExceptionLog _exceptionlog;
public UserController()
{
}
public UserController(ILogIn login, IExceptionLog exceptionLog)
{
_login = login;
_exceptionlog = exceptionLog;
}
[HttpPost]
public JsonResult GetLogInByUserIdPassword(string UserId, string Password)
{
try
{
Encrypt objEncrypt = new Encrypt();
tblLogIn objtblLogIn = new tblLogIn();
objtblLogIn = _login.GetLogInByUserIdPassword(UserId, objEncrypt.EncryptText(Password));
return Json(objtblLogIn, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
_exceptionlog.insertExceptionLog(ex);
return null;
}
}
}
here the problem is i am getting _login as null value while calling this method "GetLogInByUserIdPassword" and this method is presnt in another project. And by default it is calling default constructor but not calling the parameterized constructor. Any ideas will be appreciated.Thanks.
Can somebody please help me what am I missing or doing wrong. I am getting following error :
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:52096/api/Wotc/GetWotcDashBoardSummary?0=9&1=4&2=-&3=3&4=3&5=8&6=5&7=6&8=6&9=6'.","MessageDetail":"No action was found on the controller 'WotcAPI' that matches the request."}
wotcDashBoard.js :
var WotcDashBoardModule = angular.module('WotcDashBoardModule', []);
WotcDashBoardModule.factory('WotcDashBoardModuleService', ['$http', '$window', function ($http, $window) {
return {
GetDashBoardSummary: function (Ein) {
return $http({
url: '/api/Wotc/GetWotcDashBoardSummary',
method: 'GET',
params: Ein
});
}
};
}]);
WotcDashBoardModule.controller('WotcDashBoardController', ['$scope', 'WotcDashBoardModuleService', function ($scope, WotcDashBoardModuleService) {
var Ein = '00-00000';
WotcDashBoardModuleService.GetDashBoardSummary(Ein).then(function (response) {
$scope.Summary = response.data.Employees;
});
}]);
WotcAPIController :
[RoutePrefix("api/Wotc")]
public class WotcAPIController : ApiController
{
[HttpGet]
[Route("GetWotcDashBoardSummary")]
public async Task<IHttpActionResult> GetWotcDashBoardSummary(string Id)
{
CompanyWotcBO wotcSummary = new CompanyWotcBO();
try
{wotcSummary = await CompanyWotcBL.GetDashBoardSummary(Id);}
catch
{}
return Ok(new { WotcSummary = wotcSummary });
}
}
Route.config :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Jobs",
url: "Jobs/{id}",
defaults: new { controller = "Jobs", action = "ShowJobPosting", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "HomeInit", id = UrlParameter.Optional }
);
}
}
This is because there is a parameter name mismatch.
Changed params: Ein to params: { id: ein } in wotcDashBoard.js.
code :
return {
GetDashBoardSummary: function (Ein) {
return $http({
url: '/api/Wotc/GetWotcDashBoardSummary',
method: 'GET',
params: { id: ein }
});
}
};
There are few things which I think need's fix:
Firstly: instead of url: '/api/Wotc/GetWotcDashBoardSummary',it should be something like url: 'http://www.example.com/api/Wotc/GetWotcDashBoardSummary/id', where example.com is the domain where you have hosted your service.
Secondly:
[RoutePrefix("api/Wotc")]
public class WotcAPIController : ApiController
{
[HttpGet]
[Route("GetWotcDashBoardSummary/{id}")]
public async Task<IHttpActionResult> GetWotcDashBoardSummary(string Id)
{
CompanyWotcBO wotcSummary = new CompanyWotcBO();
try
{wotcSummary = await CompanyWotcBL.GetDashBoardSummary(Id);}
catch
{}
return Ok(new { WotcSummary = wotcSummary });
}
}
You might have to enable CORS after doing this if you get any Cross-origin-request errors.
I am using Angurlar.js to call my Web API and I am getting error as:
P01:1 Uncaught SyntaxError: Unexpected token : and in resources tab it is being shown that these braces should not be there {"ProductID1":"P01","ProductName1":"Pen","Quantity1":10,"Price1":12.0} kindly help me
this is my angular code:
var app = angular.module('store', []);
app.controller('StoreController', ['$http', '$scope', function ($http, $scope) {
$scope.display = function () {
// $http.get('http://localhost:17279/api/Product/GetProduct/' + $scope.pid).success(function (data) {
$http({
method: 'jsonp',
url: 'http://localhost:17279/api/Product/GetProduct/' + $scope.pid,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).success(function (data) {
{{data}}
});
}
}]);
below code is in my WebAPI controller
List<Product> productList = new List<Product>{
new Product{ProductID1="P01",ProductName1="Pen",Quantity1=10,Price1=12},
new Product{ProductID1="P02",ProductName1="Copy",Quantity1=12,Price1=20},
new Product{ProductID1="P03",ProductName1="Pencil",Quantity1=15,Price1=22},
new Product{ProductID1="P04",ProductName1="Eraser",Quantity1=20,Price1=27},
};
public List<Product> GetProductList()
{
return productList;
}
public IHttpActionResult GetProduct(string id)
{
var product = productList.FirstOrDefault(
(p) => p.ProductID1 == id);
if(product == null)
{
return NotFound();
}
return Ok(product);
}
Apart from this I have a product model class in WebAPI which has 4 members and their properties namely : price,quantity,productID,productname
Remove the {{data}} in your success callback. This is angular's way of binding expressions to view and should not be used within your javascript code
$scope.display = function () {
$http({
method: 'jsonp',
url: 'http://localhost:17279/api/Product/GetProduct/' + $scope.pid,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).then(function (data) {
$scope.data = data;
});
}
I have this code in my post.serv.js and in my controller I want to execute the function delete.
"use strict";
app.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
}, {
delete: {
method: 'DELETE',
isArray: false
}
});
return PostResource;
});
I already know how to get and update a post, for example in my createpost.serv.js
"use stric";
app.factory('JnttCreatePost', function ($http, $q, JnttPost) {
return {
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
};
});
and in my newpost.ctrl.js
"use strict";
app.controller('CtrlNewPost',
function ($scope, $location, JnttIdentity, JnttNotifier, JnttCreatePost) {
var email = ...;
$scope.newPost = function () {
var newPostData = {...};
JnttCreatePost.createPost(newPostData).then(function () {
JnttNotifier.notify('success', 'The post has been created');
$location.path('/');
}, function (reason) {
JnttNotifier.notify('error', reason);
});
};
});
I can't realize how to perform the delete request, I can do with a $http
In my new controller for do deletePost() function I have this:
$scope.deletePost = function () {
var pwd = JnttIdentity.currentUser.hashed_pwd;
var postidd = {
password: pwd,
id: $scope.post._id
};
var config = {
method: "DELETE",
url: '/api/post/',
data: postidd,
headers: {
"Content-Type": "application/json;charset=utf-8"
}
};
$http(config);
$location.path('/');
};
This actually already do this stuff but I want to do this without the $http like the create request, How I can do this? How do I can edit this code below for do the request?
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
In my routes.js in express I have this route:
app.delete('/api/post/', posts.deletePost);
You can either call delete on the $resource class you create (JnttPost) or call $delete on a post that's returned from the $resource class.
The $resource class already has get/save/query/remove/delete functions included so you don't need to add the delete (save is create/POST, so you need to include update with PUT).
Here's a sample of using your $resource class to call delete:
angular.module('test', ['ngResource'])
.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
});
return PostResource;
})
.run(function(JnttPost){
JnttPost.delete({id: 123123123});
});
I consume a REST service using $resource. Why is it that the error callback function is always triggered even though I get a Http: 200 (Ok) response from the server? I've tried 2 ways of setting up the callback functions and both have the same issue.
Here is the Angular controller where I consume the service:
appRoot
.controller(
'BatchTaskController',
['$scope', 'batchTaskService', function ($scope, batchTaskService){
$scope.runImportIntermediariesTask = function () {
batchTaskService.runImportIntermediariesTask().$promise.then(
function (value) { alert('success') },
function (error) { alert('error') }
);
};
$scope.runImportVantageTransactionsTask = function () {
batchTaskService.runImportVantageTransactionsTask(
function () { alert('success'); },
function () { alert('error'); }
);
};
$scope.runProcessVantageTransactionsTask = function () { batchTaskService.runProcessVantageTransactionsTask(); };
}]);
Here is the Angular service:
var angularVectorServices = angular.module('angularVector.services', ['ngResource']);
angularVectorServices.factory('batchTaskService', ['$resource' , function ($resource) {
return $resource(
"http://localhost:58655/api/BatchTask/:action",
{
action: "#action"
},
{
runImportIntermediariesTask: {
method: "POST",
params: {
action: "RunImportIntermediariesTask"
}
},
runImportVantageTransactionsTask: {
method: "POST",
params: {
action: "RunImportVantageTransactionsTask"
}
},
runProcessVantageTransactionsTask: {
method: "POST",
params: {
action: "RunProcessVantageTransactionsTask"
}
}
}
);
}]);
I am using WebApi. Here is the Server ApiController Code:
public HttpResponseMessage RunImportIntermediariesTask()
{
// _importIntermediariesTask.Run();
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
public HttpResponseMessage RunImportVantageTransactionsTask()
{
//_importVantageTransactionsTask.Run();
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
Take this as sample, try to make your action as this one below, setting up your code response code on HttpStatusCode.Whatever:
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}
Hope this helps.