Redirect a page inside a async method - c#

Requirement:
User calls a page and I display page is loading while i execute a method in background and redirect to the url that the method returns.
Tried using async method call in pageload ,pagenotredirected as already loaded.
Tried updating textbox from the async method and call textboxonchange not working as page aleady loaded
Have added the code for ajax per ur suggestion please review
I call a async method inside pageload and in the pageload I display loading message ,after the async methos completes I get a url ,iam trying to redirect to that url but iam unable to do it inside the async as the page is already loaded ,so iam updating an hidden textbox with this url and using the onchange event in that text box and redirecting but still the page is not redirected,can someone please suggest a better way to do this-Thanks
<asp:TextBox runat="server" ID="urlTextBox" Value="" Style="display:none;" AutoPostBack="true" ></asp:TextBox>
$(document).ready(function () {
$('#urlTextBox').change(function () {
var keyword = $("#urlTextBox").val();
if (keyword.length > 0) {
window.location.href = keyword;
}
});
urlTextBox.Text = url;
the urltextbox gets value inside the async method as I process a long running process inside the async to get this url
I have added a js file in which I call the c# method like this
$(document).ready(function () {
$('#outputFromCmdLine').Text = "Loading...";
GetOutputFromCommandLine();
});
function GetOutputFromCommandLine() {
$.ajax({
type: "POST",
url: "Page.aspx/ConvertToBatch", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:true,
success: function (Result) {
window.location.href = Result;
},
error: function (request, status, error) {
alert(request.responseText);
}
});
and the c# method is sync method and returns the url like this
[System.Web.Services.WebMethod()]
public static string ConvertToBatch()
{
some process
return urlstring;
}
I also added the js file name in top of aspx page ,but nothing gets called ,is this the right way to do it
<script type="text/javascript" src="/Scripts/jqueryFile.js"></script>

Instead of calling the async method from inside the page load you should call it using AJAX in JavaScript once the page is loaded. Then you can use the response from the AJAX request to retrieve the URL with which to trigger navigation to.
<script>
$(function()
{
$.ajax(
{
url: "/api/request",
}).done(function(responseUrl)
{
window.location.href = responseUrl;
});
});
</script>
This will wait for the page to be loaded, make some request to the server, and navigate to the response string (expecting the HTTP response body to be a URL).
I think you would use an ASMX web service or better yet an ASP.NET Web API controller to handle the actual request/response.
I know that with Visual Studio 2013 you can create an ASP.NET Web Forms project which includes Web API and configures them automatically to work together. If you are working with an existing project you could add Web API as a NuGet package and add the appropriate plumbing to make it work manually by simply looking at the VS2013 wizard-generated project as an example of how it is done.
EDIT:
It seems you found another way to handle AJAX calls which is using a WebMethod. WebMethods are described in this question.

Related

Ajax redirect in ASP.NET MVC

I am learning ASP.NET MVC and I am facing an issue in Ajax redirect. In normal post or get call we can return the user to some specific page like:
return RedirectToAction("AllStudents");
but using json, it's different or may be I don't know much about it.
I have posted my code in normal and also converted to Ajax.
What I have tried
Controller code in general:
[HttpGet]
public ActionResult Delete(int id)
{
stude.DeleteStudent(id);
return RedirectToAction("AllStudents");
}
and I have use Ajax which do the work successfully but it is not redirecting the user to another page, like in the above code it redirects the users to another page.
My Ajax controller code:
[HttpPost]
public JsonResult Delete(int id)
{
stude.DeleteStudent(id);
return Json("true",JsonRequestBehavior.AllowGet);
}
My Js code:
// Delete record
$("#del").click(function (e) {
e.preventDefault();
var id = $("#stid").val();
//alert(id);
$.ajax({
method: "POST",
url: "Delete/" + id,
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (err) {
console.log('Failed to get data' + err);
}
});
});
The action is performed and data is deleted but the browser stop like:
updated
My goal: I want that the data is deleted without the page refresh, like it normally does. Also please share a link, post, something which shows the page refresh using ajax. like I want to refresh a page after every 1 minute but without reloading it.
Update: The data is now deleting but the Red highlighted (page) is not refreshing, I have to manually refresh, which I don't want. I want to refresh it silently without reload it.
if you will refresh the grid only then create a timeout method are follow as:
setTimeout(function() {get grid data by ajax call}, 10000);
if you want to reload the whole page then
create one partial view.
create an action method and return PartialView().
create ajax call and getting response to add in div like divid.html(data);
if you refresh the page every 1 min then create a time out function and create a simple ajax.
setTimeout(function() { ajax call}, 10000);

Sending $ajax via jQuery to C# codebehind not working

I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?
[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})
If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)

Redirect from .ashx to .aspx using $.ajax()

If I use the solution posted here, I won't get transferred to the new page. But if i inspect the $.ajax() call in the console, the actual .aspx page seems to be in the response body. So my guess is that the .ashx gets redirected to the .aspx.
void ProcessRequest(HttpContext context)
{
context.Response.Redirect(newUrl);
}
How do I redirect the user from the .aspx page that sends the ajax request? Do I need to call a method on that .aspx from my handler.ashx?
The Response.Redirect command is nothing more than instructions to the browser to move to some other page. This commands are first a header instruction to the browser. Also there is a javascript small script that is written on the page in case the header is fail.
Now, when you make the call with Ajax (no matter if its handler or page) the results return to the page but inside the ajax buffer, the redirect headers are "eaten" and not go to the browser itself to runs them. So no redirect can be directly done via ajax call.
What you should do, is to return a signal to your ajax call, and see that signal/flag and make the redirect using javascript call window.location.replace("redirectPage.aspx")
For example, something like:
$.ajax({
url: "action.ashx",
type: "GET",
dataType: 'json',
success: function(data)
{
if(data.NeedRedirect)
window.location.replace("WhereToMove.aspx");
},
error: function(responseText, textStatus, XMLHttpRequest)
{
window.location.replace("WhereToMove.aspx");
}
});

Is this possible through javascript?

I am currently working on asp.net project. I use oodle web service. Oodle provides result via URL. I use Link to get data from the URL.
From code behind I use following code to fetch the resultant string :
string url =
#"http://api.oodle.com/api/v2/listings?
key=TEST&region=chicago&category=vehicle&format=json";
var jsonString = new WebClient().DownloadString(url);
Now , My problem is I use button click event to run that code. But is this through JavaScript ? Because If I use Javascript it will be easier to access my resultant data.
It looks like this API returns JSONP which means that you could consume it directly from javascript. For example if you use jQuery you could use the $.ajax() method:
$.ajax({
url: 'http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonOodleApi',
success: function(result) {
alert(result.current.region.id);
}
});
Here's a live demo.
And if you don't use jQuery you could simply define a callback:
var jsonOodleApi = function(result) {
alert(result.current.region.id);
};
and then include a <script> pointing to this url:
<script type="text/javascript" src="http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json"></script>
Here's a live demo.
Obviously you could inject this script tag dynamically into the DOM whenever you want to invoke the API call.
You can make Ajax requests to the page through Javascrypt.
here's a tutorial on that
If you are using some JavaScript frameworks, like JQuery, those requests would be easier to make, as the AJAX requests are kinda not cross-browser compatible.
the JQuery version
What you want is an AJAX request. It it certainly possibly to do without libraries, but due to crossbrowser issues I would recommend using a library. With jQuery for example it could look like this (in a document ready part of script):
$("#idOfButton").click(function() {
$.get('string url= #"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json', function(jsonString) {
alert('Data is now in variable jsonString!');
});
});

ASP.NET: UrlReferer has wrong value, interrogating in a static (webmethod) page called from jquery

Can anyone help? I am trying to interrogate the UrlReferer whcih should contain Google.com but it contains my current site. My web page is a standard HTM page and jquery calls a static method like so
[WebMethod]
public static void ProcessTracking(string jsonString)
Inside this method i do a standard lookup on Request.UrlReferrer like so
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
But it always contains my current domain, this was a little suspect so i created a standard asp.net page and did the same and it works 100% without issue..
So it appears that when my htm page calls via jquery my webmethod (static) and interrogates the UrlReferrer it return ALWAYS my current site which is wrong.
Does anyone know a work around?
I even tried doing something in session_start etc in global.asax but no fix.
EDIT: How i am calling the page from jquery in html
$.ajax({
type: "POST",
url: "MyService.aspx/ProcessTracking",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
},
error: function(msg) {
alert(error);
}
});
That script is hosted on your page, right? In that case, the referrer will be your site.
If you want the referrer for the page itself, then you need to pass it as an argument with your Ajax call; it won't be present in the HTTP header.
You can read the referrer of the page from the document.referrer property.
Surely it should contain your current domain, as that is webpage doing the post?
If you want to retrieve the original callers page, you'll need to store that in the original webpage, before calling your ajax code, and then passing that through.
Resources called via AJAX requests will consider the calling page as the referrer, which is why your domain is showing up as the referrer.
You had the right idea to use the Global.asax, but try hooking in to the BeginRequest method:
void Application_BeginRequest(Object Sender, EventArgs e)
{
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
}
This is working as intended. When you use AJAX to post, you are sending a request from your page (your domain!) to the target server.
One workaround would be to store the original referrer's host name in a javascript variable when constructing your page:
var referrerHost = '<%= HttpContext.Current.Request.UrlReferrer.Host %>';
Then package that into the jsonData variable you're sending to the ProcessTracking method in the ajax function's data parameter.

Categories