RazorPages return RedirectToPage not working - asp.net-core

I've got an odd thing happening. On my index page I've got an ajax call that grabs a parameter off of an SVG and then hits the following code:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
HttpContext.Session.SetObject("CurrentFilters", SearchFilters);
SearchFilters.State = state;
return RedirectToPage("/Search");
}
I'm able to attach a debugger and see everything is working fine behind the scenes. The problem, the UI doesn't ever update and take me to the Search page. If I manually navigate there all the data is loaded and everything is fine.
Not seen this behavior before and I've used the same code in previous projects.
Here is the AJAX call in case it's relevant:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
console.log(data.result);
location.reload();
});
});
});

You can change your code like bellow.
Action:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
//...
return new JsonResult(new { redirectToUrl = "/Search" });
}
In your Ajax:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
});
Test Result:

Related

How to call a method from API Controller using ajax

I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

Passing form collection with Knockout.js in asp.net MVC

I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});

Not able to change the value of a variable inside the $ajax success

I am having a curiously weird problem, here is my JS code
function ValidateUser(username) {
var userExists = "somevalue";
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Controller/Validate",
data: JSON.stringify({ username: username }),
cache: false,
dataType: "json",
success: function (response) {
alert(response);
if (response == true) {
userExists = true;
alert("user exists: " + userExists);
} else {
alert("user exists: " + userExists);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return userExists;
}
well, the action works fine and validates user correctly, but the function ALWAYS returns "somevalue".....What gives? My hunch is that it has something to do with a function scope. But how do I resolve this issue.
Because the function you're calling $.ajax from returns before the Ajax call completes.
The simple answer is to do the work you need to do in the success function, either with an immediate function (as now), or by setting success to an existing function.
You could also use jQuery's $.when function.
You can use the setting "asynch: false" too, it will lock the browser, disabling any actions while the request is active. Here is your code changed:
function ValidateUser(username) {
var userExists = "somevalue";
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Controller/Validate",
asynch: false,
data: JSON.stringify({ username: username }),
cache: false,
dataType: "json",
success: function (response) {
alert(response);
if (response == true) {
userExists = true;
alert("user exists: " + userExists);
} else {
alert("user exists: " + userExists);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return userExists;
}
You can get more information here: jQuery.ajax()

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...