Call AllowAnonymous method in AuthorizationRequired class gives me 302 error - c#

I am trying to call a method in my AccountController, which is a AuthorizationRequired class. But when method is called, the user is not yet authorized. So I have written the method like this:
[HttpPost]
[AllowAnonymous]
public ActionResult Accept()
{
string memberno = TempData["memberno"] as string;
_accountRepository.AcceptTerms(memberno);
Account acc = _accountRepository.GetAccount(memberno);
LoginViewModel loginView = new LoginViewModel
{
MemberNo = acc.AccountNo,
Password = acc.Password,
ForgotPassword = false,
RememberMe = false
};
return Login(loginView,"");
}
And my method which calls it is a $.ajax method:
function acceptTermses() {
$.ajax({
url: '#Url.Action("Accept", "Account")',
type: "POST",
success: function (da) {
alert("did it");
}, error: function (w) {
alert("FAILED");
}
});
}
But when I try to call the method, I get this in the browser:
Remote Address:::1:33405
Request URL:http://localhost:33405/Account/Accept
Request Method:GET
Status Code:302 Found
and
Failed to load repsonse data
Instead of failing my method, it does this call instead, after the 302 Found call:
http://localhost:33405/Account/Login?ReturnUrl=%2FAccount%2FAccept
And then it runs with "success", but never calls the controller method.
I have tried to do the same call to another method in the class, and that worked just fine. I have no idea why it wont run with this method.

There is a problem with return Login(loginView,"") i.e. redirecting to Login Action which is wrong in your question.
Try This :-
[HttpPost]
[AllowAnonymous]
public ActionResult Accept()
{
string memberno = TempData["memberno"] as string;
_accountRepository.AcceptTerms(memberno);
Account acc = _accountRepository.GetAccount(memberno);
LoginViewModel loginView = new LoginViewModel
{
MemberNo = acc.AccountNo,
Password = acc.Password,
ForgotPassword = false,
RememberMe = false
};
return Json({ message="success" }, JsonRequestBehavior.AllowGet)
}
function acceptTermses() {
$.ajax({
url: '#Url.Action("Accept", "Account")',
type: 'POST',
datatype:'JSON',
success: function (data) {
if(data.message=="success"){
window.location.href="/Account/Login";
}
}, error: function (w) {
alert("FAILED");
}
});
}

Related

MVC 5 AJAX Code is not accessing Controller Class Action Server Side

The intention of the code:
The intention of this code is to accept data passed to it through the scope and place in an array to be passed to a Login controller (Server Side) via AJAX.
The Problem
The AJAX code does not seem as if it is successfully contacting the serverside action.
I have tried moving the action from the login controller to the home controller: No success.
I have tried following the guidelines of those who previously ran into this issue: No success.
I have tried hardcoding the URL to the action: No success.
Below is the AJAX Call:
login: function (username, password) {
var cred = { "uname": username, "pass": password };
var response = $http({
method: "POST",
url: '#(Url.Action("CheckUser","Login"))',
data: JSON.stringify({ model: cred }),
contentType: 'application/json; charset=utf-8',
dataType: "JSON",
success: function (msg) {
if (msg) {
console.log("success: " + msg);
}
},
error: function (msg) {
if (msg) {
console.log("Error:" + msg);
}
},
failure: function (msg) {
if (msg) {
console.log("fail: " + msg);
}
}
});
Next the action code:
namespace test4.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Login()
{
return View();
}
public class UserCred
{
public string Uname { get; set; }
public string Pass { get; set; }
}
[HttpPost]
public ActionResult CheckUser(UserCred umodel)
{
Console.WriteLine("I am here");
if (!ModelState.IsValid)
{
return Content("0");
}
string uname = umodel.Uname;
string pword = umodel.Pass;
using (localtestEntities entity = new localtestEntities()) {
var user = entity.users.Where(u => u.uname == uname).FirstOrDefault();
if (user != null) {
if (pword == user.pw) {
Session["LoginID"] = user.id;
Session["Username"] = user.fname + ' ' + user.lname;
return Content(user.id.ToString());
} else {
return Content("0");
}
} else {
return Content("0");
}
}
/* Begin Assigning values */
} //End Check User
}
}
The intended result is to pass back to the client side code whether the comparison of strings passed and what is in the database matches.
A couple things:
$Http({... is not an actual ajax function. I would recommend using $.post() for [HttpPost] and $.get() for [HttpGet]. You can review this in detail from jQuery's documentation here: https://api.jquery.com/jquery.post/
That URL will not work. You can't access razor helper methods inside of JS. As is, you're literally passing #(Url.Action("CheckUser","Login")) into your url so it would look something like localhost:3000/#(Url.Action("CheckUser","Login")) which obviously is not a legit route. You're going to have to get that URL to your ajax function a different way. Some options:
1) In the header of your .cshtml file, do something like:
<script>
$(() => {
const url = `#Url.Action("CheckUser","Login")`;
//Pass that into your JS code via a constructor parameter if your JS
//is a class or by function parameter if your JS code is a function.
const myJSClassNameHere = new myJSClassHere(url);
});
</script>
2) you can just hard code the url into the ajax call. This is a viable option if you don't anticipate the url to change and/or if your standards allow it.

How to send one value after successful ajax post request to a page redirect

I am learning ASP.net MVC - 5 and I am stuck at one problem. So I need to open a URL after successful Ajax Post Request. But I also want to pass one value to the new URL's Controller Action. Below is what I have till now.
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
},
error: function (error) {
}
});
Controller Action
[AuthorizeSettings]
public ActionResult Customize()
{
//I want to be able to access TEMPVAR value here
// code removed for brevity
return View(configData);
}
Question: How to pass the TEMPVAR data to the Customize Action
Points:
I know there are some ways to pass data. TempData,Viewbag,SessionVariable, Embedding the TEMP value in URL Request, Anonymous Objects, ViewData, Static variable for the class, Global Variable, JSON. But I am totally confused how to pass data. I am newbiew please guide me here.
EDIT:
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
TEMPDATA["value"] = TEMPVAR;
},
error: function (error) {
}
});
Based on comments, you want to send data from SaveStyles to Customize. If so, you can use TempData -
public class PersistController : Controller
{
[HttpPost]
public ActionResult SaveStyles()
{
TempData["Status"] = true;
TempData["Val"] = 4;
return Json(true);
}
}
public class SettingsController : Controller
{
public ActionResult Customize()
{
bool status = Convert.ToBoolean(TempData["Status"]);
int val = Convert.ToInt32(TempData["Val"]);
return View();
}
}

controller method is not triggering in ajax post c#

My ajax post,
function getuser() {
if (window.user == undefined) {
$.ajax({
type: "POST",
url: url, // value from view file(var url = "#Url.Action("getuser", "home")";)
data: { },
async: false,
cache: false,
success: function (result) {
window.user = result.data.user;
}
});
}
}
My controller,
[Authorize]
public class HomeController
{
[HttpPost]
public JsonResult GetUser()
{
return this.Json(new { data = GetUser() });
}
}
I have removed async: false also. But my controller method is not triggering. Please correct me where I am wrong ?

Call Controller Method using Ajax request

please your help to call a method from controller using ajax request, below is my code, but error had returned says that the source of controller cannot be found.
here is my ajax code
function GetServices() {
var e = document.getElementById("catagories");
var strUser = e.options[e.selectedIndex].value;
var id = e.options[e.selectedIndex].id;
$.ajax({
url: "~/VasController/ExecuteVas/",
//url: '<%= Url.Action("GetServices", "Vas") %>',
type: 'POST',
contentType: 'application/json',
data: {"id": id},
success: function (result) {
alert(result);
}
});
}
and here is my controller method
[WebMethod]
public static string GetServices(string id)
{
return id;
}
kindly advice, i am still beginner in c# and MVC
in your controller file
public class YourControllerNameController : Controller
{
[HttpPost]
public ActionResult Dosomething(int? id)
{
//your code
return View();
}
}
then in your view
$.post('#Url.Action("Dosomething","YourControllerName")', { id: id }, function (data) {
});
You have to do the following:
1- Decorate the Action method with [HttpPost] tag
2- Remove the word 'controller' for the Ajax URL it would be 'url: "~/Vas/ExecuteVas/"
3- if 1 and 2 did not work,Try putting the Ajax URL without ~/

How to pass an object to a MVC controller via Jquery Ajax Get

I am new to jquery and I can't resolve the following problem : I want to pass an object to one of the controllers in my mvc application. Here is what I got so far:
function enterPressed() {
$(function () {
$('#textBox').keypress(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
doSomethingElse(textBox.value)
}
});
});
}
function doSomethingElse(p) {
$.ajax({
type: 'GET',
data: {string: p},
url: '"Control/AddControl/Index"',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
return true;
But every time when I press enter I end up with the fail. My controller is found in ~/Controllers/Control/AddControl. Do any of you see the problem ?
My C# code:
public class AddControlController : Controller
{
//
// GET: /AddControl/
public ActionResult Index(string control)
{
return RedirectToAction("ShowControl");
}
}
You should change value name to control, as action expected. Also you can use #Url.Action() helper for setting url param.
$.ajax({
type: 'GET',
data: { control : p},
url: '#Url.Action("Index","AddControl")',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
Finally, your action can't return redirect action with ajax response.
If you want to make redirect after successful response, you can make it in client side.
There are a few problems:
1-you are using a wrong url. The correct url is '/AddControl/Index'.
2-Your code in your controller won't work, since you are using ajax. You should return Json and handle the redirect in the client side.
3-You should allow GET through ajax:
public ActionResult Index()
{
return Json("Ok", JsonRequestBehavior.AllowGet);
}
You might want to just POST in stead of GET.
function doSomethingElse(p) {
$.post(
'#Url.Action("Index", "AddControl")',
{
control: p
},
function (data) {
alert(data);
}
);
}
You should decorate your controller action with the HttpPost attribute:
[HttpPost]
public ActionResult Index(string control)
{
return Json("I received this: " + control);
}

Categories

Resources