Handle Authentication in AJAX Calls - javascript

I am using the following code in my controller
[HttpPost]
public ActionResult SearchResultsAll(string keyword)
{
System.Threading.Thread.Sleep(1000);
string data = "Search results for " + keyword;
return Json(data, JsonRequestBehavior.AllowGet);
}
and trying an AJAX call as following
$.ajax({
url: "/Home/SearchResultsAll",
type: 'POST',
data: {
keyword: searchString
},
success: function (data) {
console.log(data);
},
error: function (jqXHR) {
console.log("ERROR");},
complete: function (jqXHR, status) {
console.log("DONE");
}
});
Instead of getting the string back, I get the HTML code for my login page - Yes the authentication is active on my HomeController
How do I tackle this in AJAX calls?

The problem with applying Authorize globally is that you have to be logged on (authorized) before you can log on or register.
[HttpPost]
[AllowAnonymous]
public ActionResult SearchResultsAll(string keyword)
{
System.Threading.Thread.Sleep(1000);
string data = "Search results for " + keyword;
return Json(data, JsonRequestBehavior.AllowGet);
}
AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions

Related

How to post js string to C# in ASP.NET Core MVC

I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}

HttpPost in MVC Controller not being called through Ajax POST

I have a controller (InformationTechnologyController). That controller contains an action (LocationChangeRequest). That action takes an optional parameter(id).
public ActionResult LocationChangeRequest(ChangeRequestType id = ChangeRequestType.WithinDepartment)
That action returns a view with the current model data.
return View(locationChangeRequest);
Within that view, there's a function that performs an ajax post (code below) to search for employee information.
Employee Search 1
The url to reach that view is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest
When a user attempts to reach that view using a route parameter, the Employee Search function does not perform.
The url to reach the view with the routing parameter is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest/1
What I discovered is the HttpPost method in the InformationTechnology controller is not being hit when using the /1 parameter in the path. Athough it seems to have to do with the parameter in the path, I can't seem to figure out how to solve the problem.
Any advice on how to handle hitting the HttpPost through the url with the parameter would be appreciated.
The HttpPost code is as follows:
[HttpPost]
public JsonResult SearchUser(string term)
{
...
return Json(results, JsonRequestBehavior.AllowGet);
}
The javascript code is as follows:
$.ajax({
url: searchUserUrl,
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data,
function (item) {
return { label: item.Name, value: item.HexKey }; }));
},
error: function (xhr, error) {
console.debug(xhr); console.debug(error);}
})
You need to define a global variable for using the $ as below.
var $=jQuery.noConflict();

Returned 404 Not Found when request user email [ASP.NET Web API]

I'm trying to get user email from ASP.NET Web API through writing an email in an input box using JQuery (to select message recipients), But the returned value is null. Are there any problems in passing process in my code?
Web API:
[AllowAnonymous]
[HttpGet]
[Route("get-reciver-email")]
public ApplicationUser GetReciverEmailId([FromUri] string email)
{
return _userManager.FindByEmail(email);
}
Client-side "JQuery":
$('#toEmail').keyup(function () {
$.ajax({
url: '/api/Account/get-reciver-email/' + $("#toEmail").val(),
method: 'GET',
success: function (response) {
console.log(response);
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
I expect to return user info based on passed email in HTML form.
Solved.
I removed [FromUri] & I used query-string (THX for #Mihai), also I modified API function to the following:
[AllowAnonymous]
[HttpGet]
[Route("get-reciver-email")]
public string GetReciverEmailId(string email)
{
return db.Users.Where(x => x.Email == email).Select(x => x.Id).Single();
}
Client-side code:
$('#toEmail').keyup(function () {
$.ajax({
url: '/api/Account/get-reciver-email/?email=' + $("#toEmail").val(),
method: 'GET',
success: function (response) {
console.log(response);
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

Ajax throwing error after calling controller

I am having some issues calling a controller method from my jquery ajax. The controller method is called and the data servername is passed in correctly. But, before my controller can return anything to the jquery, the jquery enters the error state.
Here is my jquery and controller code snippets:
$.ajax({
type: 'POST',
url: '#Url.Action("serverLookup", "QC")',
dataType: 'text',
data: { 'serverName': servername },
success: function (result) {
alert(result);
debugger;
},
error: function (result) {
debugger;
}
});
[HttpPost]
public ActionResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Content(data);
}
On top of everything. The result value given when the error is reached is not helpful at all either.
Send your response back as JsonResult
[HttpPost]
public JsonResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Json(data);
}
Return a Json:
return Json(new { result: data });
When you make an AJAX request to the controller, it needs a JsonResult.
I suppose that Your Content() return html. In that case You have to change dataType to html, Or change it according to your response.

Categories