Add URL variables with Server.Transfer in asp.net - c#

I am currently trying to add a variable to the url using Server.Transfer. I need to use Server.Transfer as I need to keep form post data which is why I can't use Response.Redirect.
I am using Server.Transfer("add_account.aspx?error=userNotFound"); but the variable is not being added to the URL.
Thanks for your help.

Usually with Server.Transfer, we use context to pass data around:
Context.Items["error"] = "UserNotFound";
Server.Transfer("add_account.aspx");
This is a state container like Session and Application, but it only persists for the current request and then goes away.

Related

Get reference to instance of the calling aspx from ashx in ASP.NET WebForm

I'm in the code behind of a generic http handler (.ashx) and I'd like to get a reference to the instance of the calling .aspx page, so I can call some methods/get some properties of it. I can easily call static methods of the page, but I'm not able to get the actual object instance.
Is there a way, without resorting to services/webmethods/whatnot? Thanks!
EDIT:
I call the ashx from the JS inside the aspx page
$.ajax({
url: "handler.ashx",
context: "my content"
}).done(function() {
alert("Done");
});
Then I update an asp:Label with the result of it.
I've found a way to do it anyway (you can do it via JQuery from JS for instance), but now I'm curious if you can do it from the code behind simply calling some pageInstance.setMyLabel(ashxResult) or something like this.
There is no direct way to modify the contents of your calling .aspx-page via server-side code.
You should (like you mention yourself) process the results of the call to your .ashx-handler with javascript.
If you would like to use some results 'serverside' I think the only option is that you write some data to the session-object during the processing of the .ashx-handler.
On the next postback of the .aspx-page you could use that data to accomplish some change. If you would like to do that, please refer to this question also:
How to access Session in .ashx file?
The instance of the page class only exists for as long as it takes to process the request and send the response back to the client. By the time the Javascript code executes and makes a request to the ashx file, the page instance has been destroyed.
ASP.NET Page Life Cycle Overview | Microsoft Docs

Session variable does not maintain value across different controllers

I am working with two controllers, they both save a value to Session but only one of the Controller manages to maintain it's value.
The line of code that saves the value is
Session["LoginDate"] = <dateTimeObject>;
and this is the same in both Controllers. The Second controller gets called from the First Controller and while in the second controller, if I set the value of Session then we're ok until I get back in the calling controller. If I call the First controller only, the value can get set and be sent back to the client.
I have tried modifying the second config file to include
<sessionState mode="InProc" timeout="30" />
and have made sure they are at the same version of .NET, MVC, etc...
Any ideas as to how to debug this? What else should I check?
UPDATE
Is there a way to pass the session state from different servers or would usign cookies be better since the cookie will be on the client browser? The new discovery is that the second controller does an
Redirect("serverOfController_1");
The controller gets initialised by the MVC core, so that it has the correct references to the context of the current request. When you create an instance of a controller yourself, that won't have any context at all, so it can't use anything from the controller interface.
For a method in that controller to work in that context, it can't rely on anything in the controller interface. If you want to set a session variable from that method, you have to get the current context and access the Session object from that:
System.Web.HttpContext.Current.Session["LoginDate"] = <dateTimeObject>;
You can also copy the controller context from the current controller after you have created the instance. That way the controller that you created will have the same context as the current controller. Example:
SecondController second = new SecondController();
second.ControllerContext = ControllerContect;
second.SomeMethod();

Register ClientScriptBlock only once during multiple postbacks

In my asp.net websites I regular uses the following methods before actually adding either custom pieces of script or registering a js file:
IsClientScriptBlockRegistered(Type, String)
IsClientScriptIncludeRegistered(Type, String)
When a page requires a custom piece of script, somewhere during PageLoad I call IsClientScriptBlockRegisterd() followed by RegisterClientScriptBlock().
if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "myKey"))
{
// Start creating ScriptBlock //
// .. //
// Actually Register the script //
ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myKey",
sbScript.ToString(), false);
}
The above code is always called once during a postback.
When a user is on the related page, while staying on that page he can cause multiple postbacks (actual postbacks, not callbacks).
During a postback the GetRegisteredClientScriptBlocks method always returns an empty collection. So IsClientScriptBlockRegistered always returns false. Therefore, for each postback I have to recreate the custom scriptblock and re-register it with the page, and re-send it to the client.
Is there a way to register a custom scriptblock and let it exist at the client for as long as the user stays on the related page, or for as long as the users sessions is active?
Thanks in advance.
Assuming you are using ASP.Net WebForms, you may use the following property to ensure whether it is postback or not:
Page.IsPostback()
Alternatively, you may pass some sort of flag/cookie/hidden variable indicating that this particular page does not need any client scripts to be registered.

Source of request in asp.net/C#

Basically, I need to know the answer to this question in asp.net/C#:
source of REQUEST
I would like one of my pages to know which page directed the user to this specific page. I've tried going through intellisense on a few different Page properties, but couldn't find it. Any help?
Sounds like your looking for Request.UrlReferrer
Documentation: HttpRequest.UrlReferrer
The request can be attained off the page:
Page.Request
If a Page instance is not available, you can get it from the current context using:
HttpContext.Current.Request
You can look at Request.ServerVariables("HTTP_REFERER") or Request.ServerVariables("URL").
Or you can use the Request object this way:
Request.Url.ToString() gives you the full path of the calling page.
If you call this in the Immediate Window without the ToString, you can see lots of information:
Request.UrlReferrer.ToString()
You're looking for the Request.UrlReferrer property.
I think you want Request.ServerVariables["HTTP_REFERER"];
EDIT:
Use #SLaks answer
We can get to know the referral Url from UrlReferrer property.
It's easy to handle in the global.asax file.
protected void Session_Start()
{
var SourceURL = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
Now we can store this value in session or somewhere and do what ever operation we would like.

Passing parameters from silverlight to ASP.net

I've made a little game in silverlight that records users scores whilst they play.
I decided it would be a lot better if I could implement a leaderboard, so I created a database in mySQL to store all the high scores along with names and dates. I have created some communications to the database in ASP.net. This works and I can simply insert and get data within the code.
It's now time to link the silverlight project with the ASP.net database communications, so I can send the users name and score as variables to my ASP.net code and then it will upload it to the database. That's all I need. Surely there must be an easy way of doing this, I just can't seem to find any ways when researching.
Thanks in advance,
Lloyd
At first you need add Generic Handler to your ASP.Net project.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string userName = context.Request["user"];
int score = int.Parse(context.Request["score"]);
//And store it in DB
}
}
After you need call this handler from SilverLight app:
string uri = HtmlPage.Document.DocumentUri.ToString();
// Remove the web page from the current URI to get the root URI.
string rootUri = uri.Remove(uri.LastIndexOf('/'),
uri.Length - uri.LastIndexOf('/'));
string diggUrl = String.Format(rootUri + "/" + "test.ashx?user={0}&score={1}", "testuser", "234");
// Initiate Async Network call to Digg
WebClient diggService = new WebClient();
diggService.DownloadStringAsync(new Uri(diggUrl));
here i used Uri Class to send parameter to asp.net, but you can send string format only.
// this code written on Silverlight Button Click Event.
Uri myURI = new Uri(HtmlPage.Document.DocumentUri,String.Format("Report.aspx?brcd={0}&acc={1}&user={2}", Brcd, Acc, User)); HtmlPage.Window.Navigate(myURI, "_blank");
below code is written on Asp.net page_load or page init event
Brcd = Request.QueryString["brcd"];// brcd value accept here.
acc= Request.QueryString["ACC"];`
user= Request.QueryString["User"];
in above code we accept the silverlight parameter in asp.net but in [] bracket put name as it is use in silverlight page because it case sensitive.
By ASP.NET, do you mean an ASP.NET Webforms app?
If so, an ASP.NET Webforms app is a method of building a UI. What you need is an API, for your Silverlight app to use programatically. For this purpose you may want to consider building an ASP.NET Webservice instead, which provides an API over HTTP.
What do you need its to send data to web server from a Silverlight application, right?
You can:
Call Javascript functions from Silverlight and, there, do a postback
Call web services with Silverlight, but make sure its in same server which your SL application came from, or you will face some XSS issues.
An easy way to do this is to have your Silverlight code create a REST URL by encoding the information into the query string, and invoking an .aspx page on the server. The page wouldn't need to return any markup; it would just handle the back-end stuff and return.
Alternatively, you could make a web service call from Silverlight to your back end.
I prefer the latter approach. It's a little more work the first time through, but it's also more general purpose and makes for generally better code in the long run.
Although technically you could use JavaScript, I wouldn't suggest it; why go backwards in tech if you don't have to?

Categories

Resources