Hi,
I have a login screen. After authentication, user_id will be saved in the session. In every registration form I want to save the registration form data and USER_ID in the database.
I have used MVC, WEB API with AngularJs to make this application. I am unable to pass session value to angularjs.
I need sample code through which I can save .Net session value using AngularJs.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.Email, model.Password);
if (user != null)
{
Session["USER_ID"] = user.Id;
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
AngularJs Controller: I want to pass the session value i.e USER_ID to this controller so that USER_ID can be saved with PROG_NAME & PROG_CODE. My PROGRAM table having USER_ID column.
$scope.save = function () {
var program = {
PROG_NAME: $scope.PROG_NAME,
PROG_CODE: $scope.PROG_CODE
};
var saverecords = programService.save(program);
saverecords.then(function (d) {
$scope.PROG_ID = d.data.PROG_ID;
loadProgram();
swal("Reord inserted successfully");
},
function () {
swal("Oops..", "Error occured while saving", 'error');
});
}
AngularJs Service:
myapp.service('programService', function ($http) {
this.getAllPrograms = function () {
return $http.get("/api/ProgramAPI");
}
this.save = function (program) {
debugger;
var request = $http({
method: 'post',
url: '/api/ProgramAPI/',
data: program
});
return request;
}
Web API:
[ResponseType(typeof(PROGRAM))]
public IHttpActionResult PostProgram(PROGRAM program)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PROGRAM.Add(program);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = program.PROG_ID }, program);
}
Please help...
What I have tried:
//save form data
$scope.save = function () {
debugger;
var USER_ID = '<%=Session["USER_ID"]%>';
var program = {
PROG_NAME: $scope.PROG_NAME,
PROG_CODE: $scope.PROG_CODE,
CREATED_BY: USER_ID
};
var saverecords = programService.save(program);
saverecords.then(function (d) {
$scope.PROG_ID = d.data.PROG_ID;
loadProgram();
swal("Reord inserted successfully");
},
function () {
swal("Oops..", "Error occured while saving", 'error');
});
}