I tried a bunch of stuff and this is what i have so far:
So i try to call this method "runTest()" from my javascript.
The method does not actually go, and it goes through as a success, so the "handleTest()" goes and also succeeds. I need it to actually call the controller function.
Javascript/Angular/JQuery
$scope.runTest = function (myTest) {
$.ajax({
method: 'POST',
Url: 'Tests/runTest',
contentType: 'application/json;',
data: myTest,
success: function () { handleTest(myTest); },
error: function () { alert('no object found'); }
});
}
function handleTest(currentTest){
var updated = { id: currentTest.id, name: currentTest.name, schedule: currentTest.schedule, description: currentTest.description, server: currentTest.server, port: currentTest.port, method: currentTest.method };
//var updated = currentTest;
$http({
method: "PUT",
url: 'http://~~api address~~/api/tests/' + (currentTest.id),
data: updated
})
.success(function (data, status, headers) {
alert("Test was successfully updated.");
$state.reload();
})
.error(function (data, status, headers) {
alert("Test could not be updated.");
$state.reload();
});
}
C# controller method
(named TestsController)
[HttpPost]
public ActionResult runTest(StandardTest myTest)
{
myTest.lastResult = MyEnum.Pass;
log.Info(myTest.name + " " + myTest.lastResult + " " + myTest.id);
return Json(myTest, JsonRequestBehavior.AllowGet);
}
Any help would be so so appreciated.
An example could be as follows:
In your c# controller
[HttpPost]
public ActionResult runTest(StandardTest myTest)
{
myTest.lastResult = MyEnum.Pass;
log.Info(myTest.name + " " + myTest.lastResult + " " + myTest.id);
if (!testPassed){
//test did not pass
return Json(new {success = false,
responseText = "Test did not pass",JsonRequestBehavior.AllowGet);
}
else
{
//Test Passed
return Json(new {success = true,
responseText= "Test Passed"},JsonRequestBehavior.AllowGet);
}
}
Try to run your web request using the angular $http service.
angular.module('YourModuleName')
.controller("ngControllerName", ["$http", "$scope", function ($http, $scope) {
/*Request to C# Controller*/
$scope.runTest = function(myTest){
var config = {
params:{myTest: myTest}
}
$http.get('/Tests/runTest', config).success(function (data) {
if(data !=null && data.success){
handleTest(myTest);
}
}).error(function (error) {
//Handle Error
});
}
}
Related
I have an ajax call (GET) to a controller action to generate and return a url (JSON). When I run the code the ajax call goes but it never hits the controller action. I get a 500 error with no response text. I'm stumped. Below is my code, Thanks!
[HttpGet]
public ActionResult ViewOrderForm(int? id)
{
if (id == null || id == 0)
{
_logger.LogInformation("Order Id " + id + " does not exisit in the database. User is unable to view form.");
return NotFound("Order Id " + id + " does not exisit in the database.");
}
return Json(new
{
newUrl = Url.Action("ViewOrder", new { id = id })
}
);
}
function viewOrderForm(id) {
$.ajax({
url: siteURLS.ViewOrderForm,
method: "GET",
data: {
id: id
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
}).done(function (data) {
//alert(data.newUrl);
window.location.replace(data.newUrl);
});
}
Believe its type instead of method in ajax property
try this ajax,
$.ajax(
{
url: siteURLS.ViewOrderForm+"?id="+id,
type: 'GET',
dataType: 'json',
success: function (data) {
window.location.replace(data.newUrl);
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
});
Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:
[HttpPost]
public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
{
if (pwd == null || repeatpwd == null)
{
ViewBag.Error = "Insira os campos obrigatórios";
}
else
{
if (pwd == repeatpwd)
{
changePwd_Entidades(Session["ID"].ToString(),pwd);
return Json(true,JsonRequestBehavior.DenyGet);
}
else
{
ViewBag.Error = "As palavras chave precisam de ser iguais";
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
Script:
<script>
$('.alt-btn').on('click', function () {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home")?pwd=' +
$('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
});
I think you are using incorrect id to get value of password field.
And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input same password .
That would be better to Send the data in the data parameter while you're using POST method
var data = JSON.stringify({
'pwd': $('#Info_pwd').val(),
'repeatpwd':$('#Info_repeatpwd').val()
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home"),
data: data,
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.
I'm trying to do a ajax request to my controller in C#, but it never reaches the controller - I get a type Error saying "query is undefined".
Here is my ajax script:
$(document).ready(function () {
$.ajax({
url: '/Account/GetAllGamesWithRoles',
type: 'POST',
data: {},
success: function (games) {
debugger;
Games = games;
BuildGames(games);
},
error: function() {
}
});
});
Here is my controller action:
[HttpPost]
public ActionResult GetAllGamesWithRoles()
{
var result = MockGames();
return new JsonResult{ Data = result, MaxJsonLength = Int32.MaxValue};
}
try this
$(document).ready(function () {
alert('called before ajax');
$.ajax({
url: "/Account/GetAllGamesWithRoles",
type: "POST",
data: {'test':'testcall'},
success: function (data) {
Games = data.Data;
BuildGames(Games);
},
error: function (request, textStatus, errorThrown) {
alert("Status: " + textStatus + "Error: " + errorThrown);
}
});
});
[HttpPost]
public JsonResult GetAllGamesWithRoles(string test)
{
var result = MockGames();
return Json{ Data = result, JsonRequestBehavior.AllowGet};
}
I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}