I am using this code to redirect to page and then want to activate a specific tab among several tabs but it doesn't work. Why ? I mean anything after redirect doesn't work or display. I debugged , it hits the code after redirect code but no effect on front end.
Response.Redirect(Request.RawUrl, false);
tabContainer.ActiveTabIndex = 1;
ShowMsg("Data Updated");
As you can see on MSDN Response.Redirect ends the current request immediately and navigates to the new Url. That is why your following code is not executed.
If you want to do some additional actions on the Url you redirect your response to, you should think about adding some Parameters, e.g. Url Parameters, that get evaluated by the new Url.
The false you are passing to the Response.Redirect just prevents that a ThreadAbortException is thrown.
Related
My web-app is .Net 6, VS-2022 Blazor WASM-hosted.
I am having a problem with the URL for the API when being called from a component.
I have three files: page: VehicleList.razor, page: VehicleEdit.Razor and component: CRUD_Vehicle.razor.
The page flow is the user navigates to 'VehicleList' and has the ability to select a vehicle to EDIT via callback function. Once selected, the flow navigates to 'VehicleEdit' where some data needs to be passed to support the embedded sub-component 'CRUD_Vehicle'.
The problem is that URL to the 'VehicleEdit' looks like this with query-string data in a comma-delimited string AND it remains there when the CRUD-component is showing.
https://localhost:7777/vehicleedit/667?par=17,Bigelow,Active
When the user makes editing changes and SUBMITs the component, the HttpClient service gets called and fails with a 400-Bad Request. I am under the impression that the query-string interfers with the api URL. Please see below. Is there a way I could set the URL to not show the query-string and only have the base-address and the UID_VEHICLE like this?
https://localhost:7777/vehicleedit/667
public async Task<Vehicle> UpdateVehicle(Vehicle pVehicle) {
// Save the edited record.
HttpResponseMessage response = await httpClient.PutAsJsonAsync<Vehicle>($"/api/vehicle/{pVehicle.UID_VEHICLE}", pVehicle);
if (!response.IsSuccessStatusCode) {
// problems handling here.
Console.WriteLine($"UpdateVehicle() Error occurred, the status code is: {(int)response.StatusCode}: {response.StatusCode}" );
}
return await response.Content.ReadFromJsonAsync<Vehicle>();
}
I have a similar construction for the editing of the Customer object, but the page that shows the CRUD_Customer component has a simple URL and works perfectly to save data to the DB. The main difference is the URL for the VehicleEdit.razor. Your comments are welcome.
Thanks.
https://localhost:7777/customeredit/17
I downloaded Postman and entered the PUT transaction and the PUT RESULT showed there was an ERROR (based on DataAnnotation for the 'StartDate'-field) that was NOT caught at the client validation code. It turns out that the TITLE text was based on what the possible cause might be. But Postman showed me the exact reason why the PUT call failed.
So, my 'answer' is: Use Postman to simulate the 'httpClient.PutAsJsonAsync'-call to observe the result-details to pinpoint the reason for the '400-Bad Request' return from the service.
I have developed a login page for a tracker. I have verified the username and password by validating the same against the DB.
When the validation is successful, I have just set the session variable with username as it is required throughout the session. But the session variable changes when it is redirected to the next page.
When retrieving the username in the next page, the session variable has been changed. The code is pasted below. Please help.
Code in Login page:
if (isValidUser)
{
Session["LoginUserName"] = Name;
Response.Redirect("xxx.aspx",false);
}
Code in xxx.aspx:
User= Session["LoginUserName"].ToString();
//Getting different value while retrieving User from session.
If you specify endResponse: false, then processing of the page & any events continues despite the Redirect which was added to the output stream. This could well change the Session.
Try calling Redirect without the endResponse: false parameter:
Response.Redirect("xxx.aspx");
If you specify endResponse: true or if you leave it out entirely, then processing of the page is silently aborted after the Redirect with a harmless ThreadAbortException. AFAIK this is the normal way of doing a Redirect, and you need to have good reasons to NOT abort after a Redirect, also you need to take great care through all your remaining code because page processing continues.
I have a registration form and want to transfer the user to the success page, telling him that an email was sent to his email. I need to transfer his email from the register page to the success page.
I found about Server.Transfer, but I can't find out how to send parameters. I don't want to use query string as I don't like revealing information in the URL.
What is the proper way (if possible) to do this?
Server.Transfer("destination.aspx", true)
You might see that the above code contains the name of the page to which the control is transferred and a Boolean value ‘True’ to indicate to preserve the current form state in the destination page.
Set a property in your login page and store in it, the email.
Once this is done, do a Server.Transfer("~/SuccessPage.aspx", true);
On the other page, where you redirected, you should check something like that :
if(this.PreviousPage != null) {
((LoginPageType)this.PreviousPage).MyEmailProperty;
}
When you using server transfer you just move execution to different server handler , user will no see the new url or the parameters so it safe to make this transfer.
I would rather recommend that you do it differently.
When the user clicks the register button, you verify it all and then send the email from the still current page (so you need not transfer data to another page at all). If all went well, you just redirect:
Response.Redirect("/order/success.aspx");
If something was wrong (validation errors, sending email caused an exception) you are still on the right page for a retry. I would not use Server.Transfer at all in most cases.
You'll have to persist the value somewhere. The obvious options are in the Session object, or in a database.
For this kind of use case. You can use Context.Items to save the data with a key and read the value using the same key in the child page you are doing the Server.Transfer. Context.Items are sort of per request scoped cache for you.
Context.Items['DataKey'] = Data;
Server.Transfer("~/AnyRouteRelativePath", true);
I have used location.href to redirect next page, but now i want to back to this page, how can I do?
in my case, i cannot use Request.UrlReferrer.PathAndQuery, so any suggestion?
Since you are using location.href to change the URL, your browser is going to kick off a new request/response cycle. Thus to your server, there is no referrer - this is a whole new request.
The most direct approach to solve your problem would be to add a referrer-url parameter to your new URL, which you can then pick up on the server side.
eg:
control.location.href = "newpage.aspx?referrer-url=thispage.aspx";
and on the server:
string referrerUrl = Request["referrer-url"];
If the previous URL is one that you own/can predict (e.g. the user came from page A or page B), you could use a trick like this one: http://www.merchantos.com/blog/makebeta/tools/spyjax
When i POST the page using the following code, the Response.write("Hey") doesn't write the content ("Hey") to the parent page
<form method="post" name="upload" enctype="multipart/form-data"
action="http://localhost:2518/Web/CrossPage.aspx" >
<input type="file" name="filename" />
<input type="submit" value="Upload Data File" name="cmdSubmit" />
</form>
But When i use following code , and POST the data, the Response.write("Hey") can be obtained in the parent page
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
In the CrossPage.aspx i have the following code
if (!Page.IsPostBack)
{
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
Response.Write("Hey");
}
I don't have any code in the Page_Load event of parent page.?
What could be the cause? I need to write the "hey" to the Parent page using the first scenario. Both the application are of different domain.
Edit: "Hey" would be from the CrossPage.aspx. I need to write this back to the Parent Page
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
You almost hit on the reason yourself:
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
Your form takes the user to CrossPage.aspx, so the parent page is gone, now the previous page in the user's history.
It sounds like you are trying to do some sort of asynchronous file upload. Try looking for AJAX file upload examples, something like this: How can I upload files asynchronously?
Probably it is because you have the code in an
if (!Page.IsPostBack) block? this code will be executed only the page is not loaded on a post-back.
(HttpWebResponse)requestToSender.GetResponse(); will trigger a GET request, that's why your code is working when you call Crosspage.aspx using that code.
You are treating the page like a service. E.G. Start at ParentPage.aspx > pass data to ServicePage.aspx for processing > write response back to ParentPage.aspx for display.
You got it to work with C# by passing the duty back to the server, where state can easily be maintained while crossing page boundries. It's not so simple when you try to solve the problem without C#. This isn't a Winform app. As NimsDotNet pointed out, changing the method to "get" will get you closer, but you will get redirected to CrossPage.aspx and lose the calling page.
You said you are on "different domains". By this I think you mean your using two different IIS servers. The C# solution should still work in this scenerio, just as you've shown. Just add a Response.Write() of the fromSender object. There's nothing you've told us that makes this not technically possible. Still, if you want a client side solution you could use javascript to make the get request without getting redirected.
This post shows you how to make a get request with JQuery.
I say your aFile.SaveAs(Server.MapPath(".") + "/".... is throwing an exception. try commenting it out and testing it.
UPDATE:
I'm guessing it works from a HttpWebRequest because there is no file being posted therefore the file loop is skipped. when posting from the HTML you have a file input so your file loop is getting used and resulting in the save logic being executed. so again, that leads me to think it's your save logic
Also,I think you have a try catch statement wrapped around all this that is catching exception so u have no idea what's going wrong. If that's the case, never do that. You rarely ever want to catch exception.
After quick glance at ur save logic, replace "/" with #"\". Server.MapPath(".") returns the path using back slashes not forward slashes.
I would suggest changing CrossPage.aspx into an .ashx HttpHandler. The Page.IsPostBack may not be working correctly because it is expecting ViewState and other hidden ASP.net form fields that tell it that it's a post back from an ASP form. You also don't need to go through the whole Page life cycle functionality that ASP.net Webforms goes through.