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

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.

Related

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();
}
}

Asp.Net and Angular trying to send an Array of Objects to a Post API

I'm using the USDA food database to try to make an app that will tell you if you've gotten your daily recommendations of vitamins. I'm getting data just fine, but I'm wondering if it was possible to send that data from Angular to the C# api, so I can add the array of strings and int to a total count model.
How would I route this and what kind of data should I tell the API to expect?
The error I'm getting right now is:
Message: "No HTTP resource was found that matches the request URI 'http://localhost/api/apiFood[object Object]'."
MessageDetail: "No type was found that matches the controller named 'apiFood[object Object]'."
I've tried :
public IHttpActionResult Post([FromUri]ValueVM toEat)
{
return Ok();
}
just to see if it would route, but it didn't work out.
I'm sending the data with an ngclick="add(display)" which goes to this function in the controller:
$scope.add = function (display) {
FoodFactory.add(display).then(function (data) {
});
};
and this function in the factory:
o.add = function (display) {
var defer = $q.defer();
var config = { contentType: 'application/json' };
$http.post('api/apiFood' + display, config).success(function (data) {
defer.resolve(data);
});
return defer.promise;
};
In your model
public class toEat
{
public int id {get;set;}
public string name {get;set;}
}
In your ApiController
public class EatController : ApiController
{
[HttpPost]
public HttpResponseMessage Post(List<toEat> list)
{
return Ok();
}
}
Your request
function Request() {
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: (your serialized array),
async: false,
success: function(data) {
console.log(data);
}
});
}

Call AllowAnonymous method in AuthorizationRequired class gives me 302 error

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");
}
});
}

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);
}

Using AJAX in a Shared MVC Component

I have AJAX working for a single page, but I want it to work across all pages. How can I accomplish it?
Here is the JavaScript in scripts.cshtml:
function changeTab(tabId) {
var url = "Home/changeTab/" + tabId;
$.ajax({
url: "Home/changeTab/" + tabId,
success: function (tab) {
var t = tab;
$("#menu1").html(t);
}
});
}
I have a component Home.cs:
namespace Web.Controllers
{
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
[AcceptVerbs("GET")]
public JsonResult changeTab(int id)
{
var saveTab = id;
string username = User.Identity.Name;
[...]
return Json(username, JsonRequestBehavior.AllowGet);
}
}
}
The code works well on the Home page, but not on any other. Where do I place the changeTab function so that every page can call it?
try change your script into the following :
function changeTab(tabId) {
var url = '#Url.Action("changeTab", "Home")/' + tabId;
$.ajax({
url: url,
success: function (tab) {
var t = tab;
$("#menu1").html(t);
}
});
}

Categories

Resources