I am beginner in Angularjs I want to have in my web api controller two post methods: one for registration and one for login. Here is my web api controller post methods:
//[EnableCors(origins: "*", headers: "*", methods: "*")]
// [ActionName("register")]
// [HttpPost]
public HttpResponseMessage PostRegister(Users Student)
{
if (ModelState.IsValid)
{
Random rnd = new Random();
int card = rnd.Next(52);
Student.user_id = card;
// _usertManager.AddUser(Student);
var activateToken = WebSecurity.CreateUserAndAccount(Student.user_mail, Student.password, Student);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Student);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Student.user_id }));
// _mailManager.Sendmail("salah.rzzaz90#gmail.com", "salahsayedrzzaz#gmail.com","dd","dd");
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
////[EnableCors(origins: "*", headers: "*", methods: "*")]
//[ActionName("Login")]
//[HttpPost]
public HttpResponseMessage PostLogin(string userMaill, string passwordd)
{
if (ModelState.IsValid)
{
_usertManager.Login(userMaill, passwordd);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userMaill);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { userMaill = userMaill }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
my angular service :
this.post = function (Users) {
var request = $http({
method: "post",
url: "/api/HomeApi",
data:Users
});
return request;
}
this.post = function (userMaill, passwordd) {
var request = $http({
method: "post",
url: "/api/HomeApi",
data: { userMaill: userMaill, passwordd: passwordd }
});
return request;
}`
my angular controller :
$scope.save = function () {
var Users = {
user_id: $scope.user_id,
user_mail: $scope.user_mail,
fullname: $scope.fullname,
mobile: $scope.mobile,
secondmail: $scope.secondmail,
password: $scope.password,
type: $scope.type
};
var promisePost = CRUD_OperService.post(Users);
promisePost.then(function (pl) {
$scope.user_id = pl.data.user_id;
GetAllRecords();
$scope.Message = "Student Updated Successfuly";
ClearModels();
}, function (err) {
console.log("Err" + err);
});
};
$scope.login = function () {
var userMaill = $scope.userMaill;
var passwordd = $scope.passwordd;
var promisePost = CRUD_OperService.put(userMaill, passwordd);
promisePost.then(function (pl) {
$scope.user_id = pl.data.user_id;
GetAllRecords();
$scope.Message = "done";
ClearModels();
}, function (err) {
console.log("Err" + err);
});
};
My problem is that when I click register and login scope it calls PostRegister.
Related
I have the follow Ajax call that points to a controller function:
<script type="text/javascript">
$(document).ready(function () {
$('#AddNote').click(function () {
$('#AddNote').addClass("disabled");
var txtNote = document.getElementById('note');
var result = document.getElementById('result');
result.innerText = "Adding note...";
$.ajax({
url: "#Url.Action("AddNoteAsync", "Leads")",
type: "POST",
data: { leadId: #Model.Id, note: txtNote.value },
async: true,
success: function (data) {
// removed
},
});
});
});
</script>
When I click the AddNote button I see the "Adding note..." message display and then nothing else happens. When I check the console in chrome, it reads:
:44309/Leads/AddNoteAsync:1 - Failed to load resource: the server responded with a status of 400 ()
So I know 400 means bad request but I'm not sure why it's happening. I've tried:
Added quotes to the "leadId" and "note" field in data - made no difference.
Added alert boxes to show the value of #Model.Id and txtNote.value before the AJAX call to verify they are correct - they are.
Put a breakpoint in the AddNoteAsync function in my controller - it's never hit
Hard coded the url field to /Leads/AddNoteAsync - made no difference
Since the controller function is never being hit I'm assuming something is wrong with the &.ajax part but I cannot figure out what.
Edit: The controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddNoteAsync(int? leadId, string note)
{
ViewData["AddedNote"] = false;
if (leadId == null)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
var lead = await _context.Leads.FirstOrDefaultAsync(m => m.Id == leadId);
if (lead == null)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
var ownsLead = await LeadBelongsToCurrentUser(leadId.Value, User.Identity.Name);
if (!ownsLead)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
_context.LeadNotes.Add(new LeadNoteModel()
{
LeadId = leadId.Value,
Note = note,
NoteDate = DateTime.Now
});
await _context.SaveChangesAsync();
ViewData["AddedNote"] = true;
return Content("Success");
}
You should accept parameters as Model while making POST request(Recommended). Proposed Model will be -
public class NoteModel
{
public int? leadId { get; set; }
public string note { get; set; }
}
and Action can be -
public async Task<IActionResult> AddNoteAsync(NoteModel model)
{
}
Also Jquery can be -
<script type="text/javascript">
$(document).ready(function () {
$('#AddNote').click(function () {
$('#AddNote').addClass("disabled");
var txtNote = document.getElementById('note');
var result = document.getElementById('result');
var postData = { leadId: #Model.Id, note: txtNote.value };
result.innerText = "Adding note...";
$.ajax({
url: "#Url.Action("AddNoteAsync", "Leads")",
type: "POST",
data: JSON.stringify(postData),
async: true,
success: function (data) {
// removed
},
});
});
});
Fixed this. I was missing this from my AJAX request:
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="f"]').val());
},
And this from my Startup.cs:
services.AddAntiforgery(options =>
{
options.FormFieldName = "f";
options.HeaderName = "XSRF-TOKEN";
});
I'm trying to return a object from from WebAPI HttpPost controller method but the object isn't getting back to my AngularJS service though the post was successful. The controller method is being called as I can see its results in our database.
The WebAPI method is being called with the following code
erm.service('ERM_ERWeb_MobileSync_Service', ['$http', '$rootScope', 'ERM_Common_Factory', 'ERM_Common_Service',
function ($http, $rootScope, ERM_Common_Factory, ERM_Common_Service) {
this.SendData = function (payload) {
console.log('ERM_ERWeb_MobileSync_Service.SendData called...');
$http.defaults.headers.common.Authorization = 'Basic ' + ERM_Common_Service.Base64Encode(ERM_Common_Factory.GenAuthString());
$http({
url: ERM_Common_Factory.GetWebAPILocation() + '/API/MobileSync/ConsumeData',
dataType: 'json',
method: 'POST',
data: payload,
headers: {
"Content-Type": "application/json"
}
})
.then(function (response) {
$rootScope.$emit('ERM_ERWeb_MobileSync_Service_SendData_Complete', {});
},
function (error) {
$rootScope.$emit('ERM_ERWeb_MobileSync_Service_SendData_Error', {});
});
};
}]);
This is the controller method.
[HttpPost]
[Route("ConsumeData")]
[ERMobileInstanceAuth]
public IHttpActionResult ConsumeData([FromBody]MobileSyncPayload msp)
{
try
{
_individualService.SetNoShows(msp.NoShows.Select(i => (Models.Data.Instance.T_Individual)i).ToList());
_flightService.SetFlightTimes(msp.Flights.Select(f => (Models.Data.Instance.T_FlightLog)f).ToList());
Dictionary<Guid, int> vNums = new Dictionary<Guid, int>();
foreach (Voucher v in msp.Vouchers)
{
Dictionary<Guid, int> vNumsTemp = _voucherService.SyncVouchers(new List<Models.Data.Instance.T_Voucher>() { v });
vNums = vNums.Concat(vNumsTemp).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
_voucherLineService.SyncVoucherLines(v.VoucherGUID, v.VoucherLines.Select(vl => (Models.Data.Instance.T_VoucherLine)vl).ToList());
_cashPaymentService.SyncCashPayments(v.CashPayments.Select(cp => (Models.Data.Instance.T_CashPayment)cp).ToList());
_cardPaymentService.SyncCardPayments(v.CardPayments.Select(cp => (Models.Data.Instance.T_CardPayment)cp).ToList(), true);
List<CardPaymentAttempt> acpa = new List<CardPaymentAttempt>();
foreach (CardPayment cp in v.CardPayments)
{
acpa.AddRange(cp.CardPaymentAttempts);
}
_cardPaymentAttemptService.SyncCardPaymentAttempts(acpa.Select(cpa => (Models.Data.Instance.T_CardPaymentAttempt)cpa).ToList());
}
var returnobject = new { Response = ConvertToList(vNums) };
return Ok(returnobject);
}
catch (Exception e)
{
Logging.CreateLogEntry("DataService", Logging.ExceptionHandler.Format(e, Logging.ExceptionHandler.LogLevel.Exception));
return InternalServerError();
}
}
There must be something simple I'm missing but I can't see what it is. Anyone got any ideas?
Helps if I return the post data object in my emit
$rootScope.$emit('ERM_ERWeb_MobileSync_Service_SendData_Complete', { Response: response.data.Response });
I'm trying out AngularJS in combination with NET Core. Currently trying to parse a "string username", "string password" and "bool rememberMe", but both strings are null no matter what I do. I've even tried parsing a constant value as seen below, the parameter "test", but even that doesn't work. I've confirmed in Fiddler that the script is in fact parsing the value, so the controller basically just can't "fetch it".
Below is my AngularJS loginController code.
var login = angular.module('login', []);
login.controller('LoginController',
[
'$scope', '$http', '$window', function ($scope, $http, $window) {
$scope.submit = function () {
var data = { test: ':D' };
$http({
method: 'POST',
url: '/admin',
data: data
}).then(function success(response) {
alert(response.data.test);
});
}
}
]);
Below is the code for my ActionResult meant to fetch the value being posted to it.
[HttpPost]
public IActionResult Index(string test)
{
return Json(new
{
test,
bla = "BLA"
});
//if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
//{
// if (UserSystem.Login(username, password, rememberMe, HttpContext))
// {
// HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
// return Json(new
// {
// returnUrl = "/admin/dashboard"
// });
// }
//}
//HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
//return Json(new
//{
// error = "Username and/or password do not match"
//});
}
I've also tried specifying the Content-Type, but also without luck. Either way, in Fiddler the request always seems to per default be application/json.
I hope someone can help me. Thanks!
The solution was to request an object in the controller, rather than "string username", "string password" and "bool rememberMe".
The controller now looks like this:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
[HttpPost]
public IActionResult Index([FromBody]LoginModel model)
{
if (!string.IsNullOrEmpty(model.Username) && !string.IsNullOrEmpty(model.Password))
{
if (UserSystem.Login(model.Username, model.Password, model.RememberMe, HttpContext))
{
HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
return Json(new
{
returnUrl = "/admin/dashboard"
});
}
}
HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new
{
error = "Username and/or password do not match"
});
}
And the AngularJS controller now looks like this:
var login = angular.module('login', []);
login.controller('LoginController',
[
'$scope', '$http', '$window', function ($scope, $http, $window) {
$scope.submit = function () {
var data = {
username: $scope.username,
password: $scope.password,
rememberMe: $scope.rememberMe
};
$http({
method: 'POST',
url: '/admin',
data: data
}).then(function success(response) {
$window.location.href = response.data.returnUrl;
}, function fail(response) {
swal('Error!', response.data.error, 'error');
});
}
}
]);
I use $http request to call MVC controller and return data in JSON format. But i not able to get the result in javascript/angualr js. It return entire HTML page. Where i made the mistake?
myapp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.toggle = function () {
$http({
url: "/Admin/FilterMember",
method: "GET",
params: { id: $('#txtsearch').val() }
}).then(function (result) {
alert(result);
});
};
}]);
Above is angular script in JS file.
public ActionResult FilterMember(string id)
{
SqlParameter[] SqlParam = { new SqlParameter("#Filter", id) };
DataTable dTable = MasterMindDB.dTableSP(DbConn, "SP_Get_MemberList", SqlParam);
List<Member> member = new List<Member>();
foreach (DataRow row in dTable.Rows)
{
member.Add(new Member
{
MemberName = row["Member ID"].ToString(),
Email = row["Email"].ToString(),
JoinDate = row["Join Date"].ToString(),
Status = row["Status"].ToString()
});
}
return View("Member", Json(member, JsonRequestBehavior.AllowGet));
}
Above is MVC controller
This action is for the FilerMember view
[HttpGet]
public ActionResult FilterMember () {
return View();
}
This action will be called from the client side view. No need to return a ViewResult, just the data
[HttpGet]
public ActionResult GetMemberById(string id) {
SqlParameter[] SqlParam = { new SqlParameter("#Filter", id) };
DataTable dTable = MasterMindDB.dTableSP(DbConn, "SP_Get_MemberList", SqlParam);
List<Member> member = new List<Member>();
foreach (DataRow row in dTable.Rows) {
member.Add(new Member {
MemberName = row["Member ID"].ToString(),
Email = row["Email"].ToString(),
JoinDate = row["Join Date"].ToString(),
Status = row["Status"].ToString()
});
}
//Just return JsonResult.
return Json(member, JsonRequestBehavior.AllowGet);
}
Updated client
myapp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.toggle = function () {
$http({
url: "/Admin/GetMemberById",
method: "GET",
params: { id: $('#txtsearch').val() }
}).then(function (result) {
alert(result);
});
};
}]);
Grettings friends. So i have been researching this site for a looong time and i have not gotten a satisfactory answer to my question.
This is my Controller:
public ActionResult EliminarLibro(string bookId)
{
bookModel ModeloLibro = new bookModel();
ModeloLibro.EliminarLibro(bookId);
TempData["message"] = "Se ha eliminado el libro correctamente.";
return RedirectToAction("GestionBiblioteca");
}
And this is my Ajax in a view:
var myBookId = $('.parrafo-codigo').text();
$.ajax({
type: "GET",
url: "/Home/VerificarEliminarLibro",
data: { bookId: myBookId },
datatype: "json",
success: function (data) {
// $('#result').html(data);
if (data.esteLibroEstaPrestado == true) {
$('#delModal').modal('hide'); // Quito modal de pregunta si se elimina
$('#errModal').modal('show'); // Muestra modal de error
} else {
window.location.href = '/Home/EliminarLibro/' + myBookId;
}
}
});
The question is: how to make ActionResult EliminarLibro inaccessible via URL (for example XXXX/Home/EliminarLibro/0000532307) but is need to be called from ajax?
Done!
Thanks to Amr ElGarhy:
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpNotFoundResult();
}
}
}
And the Controller:
[AjaxOnly]
public JsonResult VerificarEliminarLibro(string bookId)
{
bookModel ModeloLibro = new bookModel();
bool HayLibrosPrestados = ModeloLibro.VerificarLibroPrestado(bookId);
if (HayLibrosPrestados == true)
{
return Json(new { esteLibroEstaPrestado = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { esteLibroEstaPrestado = false }, JsonRequestBehavior.AllowGet);
}
}
if (Request.AjaxRequest())
{
// The Code
}
else
throw new HttpException(404, "");