Asp.Net CultureInfo switching: trying to avoid non postback calls - asp.net

As if in this article I implemented an easy way to switch between languages on a website.
The issue is if I want to switch languages with a dropdown list, and leave the last selected language on the dropdown list control's view.
Every article I've seen about CulturalInfo-switching sends a Server.transfer() call right after the language switch, and that event causes the non-postback page reloading, including my dropdownlist control which realoads from default position.
I tried a response.redirect(), but it still is a non postback call
I think I need a way to check if it's a Server.transfer() call in the page load, but still haven't found a way to develop this
Thank you.

Assuming you followed the same approach as in that article, how about this:
string path = this.Request.Path;
if (path.LastIndexOf('?') > 0)
path += "&lang=" + senderLink.CommandArgument;
else
path += "?lang=" + senderLink.CommandArgument;
this.Server.Transfer(path);
Then, on the page that this.Server.Transfer executes, get lang value from this.Request.QueryString["lang"], and set the dropdown's SelectedItem appropriately.
Alternatively, keep Server.Transfer(Request.Path);, but on the receiving page, parse Session["MyCulture"] instead to set the dropdown. +1

Related

ASP.Net Grid View return to page index

I know others have had a similar issue as me, but no one so far seems to have a solution to it. Basically, I have a simple GridView with a pager and I can get the page index from it (GridView1.PageIndex etc..). But how can I retain this when a user clicks on a hyperlink bound in the Gridview to another page, update some details, then come back to the page with the GridView. So they go to page 4, click the link, update details, then go back.
I can set the value in the session and get it form the page I go to, but on databound I am checking for it and trying to set it, but it just does not work. Is there a built-in function that Microsoft thought of?
Ok, so after sucking on some caffeine I discovered that I needed to set the new Page Number on PageIndexedChanged to a session variable (best option) and on DataBinding check the session and if it exists, get the value and apply it, otherwise set it to 0 (page 1) - works a treat, hope it helps someone else.

ASP.NET Forms Parameters on Links

Ok, let me start this with I am more of an MVC person. I have a result set that I am trying to add paging. All I really want is a previous and next button on my page which are Link controls. I need these controls to post back to the same page, but have a query parm like page=4. How do I add these links? I see the PostBackUrl property on the link. Should I just use Request.Url and stuff it into PostBackUrl? Then I have to do string searches on the parm... it gets nasty. Is that the only way? I have tried ViewState, please dont suggest that... it is unpredictable garbage as far as I am concerned.
The PostBackUrl property is for cross-page postbacks, you don't want to do that.
If you want to use a POST, you can use a LinkButton, handle the click event, and rebind your result set. Something like
public void BackButton_Click(object sender, EventArgs e)
{
// Get existing page from session, viewstate, etc
// RebindGrid
}
If you want to use a GET, you can use a HyperLink and set the NavigateUrl property to the correct Url. Something like
int page;
if( !int.TryParse(Request.QueryString["page"], out page) )
page = 1;
if( page > 1 )
BackUrl.NavigateUrl = Request.Path + "?page=" + (page-1).ToString();
else
NextUrl.NavigateUrl = Request.path + "?page=" + (page+1).ToString();
// Note: not syntax/bounds checked
Edit:
Perhaps what you're looking for a Post-Redirect-Get pattern?
Response.Redirect(HttpContext.Current.Request.Path + query, true);
You're talking about ASP.NET Webforms or MVC?
If you're talking about Webforms I don't think that you'll have success on that. I believe that you'll need to control this move between your pagination with Session or other way or re-bind your data for each page.
What I ended up doing was putting hiddens on the page for the vars I needed to pass back, then I read those. This is things like page number, which allows me to calculate prev and next page. Sorry to submit my own answer but this was a little odd and I thought I would tell what I ended up doing.
View state for some reason was empty every time, so it was doing me no good. This is in a DNN app, and I didnt want to spend time figuring out why viewstate was messed up.

Is there any way to modify query strings without breaking an ASP.Net postback?

From reading here and around the net, I'm close to assuming the answer is "no", but...
Let's say I have an ASP.Net page that sometimes has a query string parameter. If the page has the query string parameter, I want to strip it off before, during, or after postback. The page already has a lot of client-side script (pure JavaScript and jQuery).
As an example, say I load:
http://myPage.aspx?QS=ABC
The QS parameter is necessary to control what appears on the page when it first loads and is set by the page that "calls" it. myPage.aspx has form elements that need to be filled in and has a submit button that does a postback. When the page completes the postback, I need to returned URL to be:
http://myPage.aspx
in order to avoid the client-side code that is called when the query string is present. In other words, after a submit I don't want the client side actions associated with the query string parameter to fire. I know I could append the form contents to the URL as query string parameters themselves and just redirect to the new URL and avoid the submit/postback, but that will require a lot more type checking on the codebehind to avoid bad data and casual spoofing. I supposed I could also set a hidden field in the codebehind and look at it along with the query string to cancel the client-side behavior if I am coming back from the postback, but that still leaves the query string intact basically forever and I want to get rid of it after the initial page load.
Any ideas or best practices?
PS - Is there anything I can do with the Form.Action property that won't break the postback behavior?
I would use an HTTPModule to intercept and rewrite the URL and query as it came in. I'm not 100%, but I don't believe this has any impact with viewstate.
It sounds (and looks) complex, but it's actually fairly trivial and open to a ton of refinement and extension (as per .NET in general).
iam not sure this is what you are looking for, but if understand correctly you could do this:
-on page load check for the QS value, if its not there use a hidden input field.
-first time page loads with QS, do your normal processing and store QS value in a hidden input field.
-if no QS then use the hidden input value
-after postback, you could redirect to the same page, at that point you could user Request.Form[] to retrieve the hidden input field, still load the data properly but get rid of the QS.
it made sense in my head, i am not sure it make sense now, but i'll let you decide.
It is probably bad practice, but in those cases (and ones I just need to 'reset' the page), I simply do a Response.Redirect to the same page.

Postback with Modified Query String from Dropdown in ASP.NET

My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).
They can select a report using two methods. With SelectedReport=MyReport in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.
My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want SelectedReport=MyNewReport in the query string and the page to post back.
At the moment it's just doing a normal postback, which leaves the SelectedReport=MyReport in the query string, even if it's not the currently selected report.
Edit: And I also need to preserve ViewState.
I've tried doing Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true) in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.
Maybe I'm asking the impossible or going about it completely the wrong way.
#Craig The QueryString collection is read-only and cannot be modified.
#Jason That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page.
EDIT: Here is some quick and dirty code that is indicative of what would do the trick:
<script>
function changeReport(dropDownList) {
var selectedReport = dropDownList.options[dropDownList.selectedIndex];
window.location = ("scratch.htm?SelectedReport=" + selectedReport.value);
}
</script>
<select id="SelectedReport" onchange="changeReport(this)">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example).
#Ray: You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
If it's an automatic post when the data changes then you should be able to redirect to the new query string with a server side handler of the dropdown's 'onchange' event. If it's a button, handle server side in the click event. I'd post a sample of what I'm talking about but I'm on the way out to pick up the kids.
Have you tried to modify the Request.QueryString[] on the SelectedIndexChanged for the DropDown? That should do the trick.
You could populate your dropdown based on the querystring on non-postbacks, then always use the value from the dropdown. That way the user's first visit to the page will be based on the querystring and subsequent changes they make to the dropdown will change the selected report.
The view state only lasts for multiple requests for the same page. Changing the query string in the URL is requesting a new page, thus clearing the view state.
Is it possible to remove the reliance on the view state by adding more query string parameters? You can then build a new URL and Response.Redirect to it.
Another option is to use the Action property on the form to clear the query string so at least the query string does not contradict what's displayed on the page after the user selects a different report.
Form.Action = Request.Path;
You can use the following function to modify the querystring on postback in asp.net using the Webresource.axd script as below.
var url = updateQueryStringParameter(window.location.href,
'Search',
document.getElementById('txtSearch').value);
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("searchbutton", "",
true, "aa", url, false, true));

Double postback issue

I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.
I have checked and checked the code, and I can't find the cause.
Here are both call stacks which end in a page_load
First postback (generated by teh ComboBox's autopostback)
Postback call stack (broken)
Second postback (this is what I want to find why it's happening)
alt text (broken)
Any suggestion? What can I check?
It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes:
A check was added to the combo's onchange with an if, if the condition was met, an explicit call to the postback function was made.
If the combo was set to AutoPostback, asp.net added the postback call again, producing the two postbacks...
The generated html was like this:
[select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"]
First thing I would look for is that you don't have the second ComboBox's AutoPostBack property set to true. If you change the value in the second combo with that property set true, I believe it will generate a postback on that control.
Do you have any code you could share? Double post backs plagued me so much in classic ASP back in the day that it was what finally prompted me to switch to .NET once and for all. Whenever I have problems like these for .NET, I go to every CONTROL and every PAGE element like load, init, prerender, click, SelectedIndexChanged, and the like and put a breakpoint.
Even if I don't have code there, I'll insert something like:
Dim i As Integer
i = 0
I am usually able to pinpoint some action that I wasn't expecting and fix as needed. I would suggest you do that here.
Good luck.
Check Request.Form["__EVENTTARGET"] to find the control initiating the postback - that may help you narrow it down.
Looking at the callstacks, and some Reflectoring (into ASP.NET 2 - I don't have 1.1 handy) - it looks like SessionStateModule.PollLockedSessionCallback is part of the HttpApplication startup routines. It may be possible that your app is being recycled - I'm pretty sure an event gets written into the Event log for that.
My only other suggestion would be Fiddler or something on the client to capture HTTP traffic.
This is very old post, but people still looking at this for solution exactly same as I did last week.
Like Grengby said Double events are primary reasons - but removing one of them is not allways an option. Atleast on my case and I had to resolve this on 3rd party's application.
I added following script and amended ASP form on masterpage:
<script>var Q = 0;</script>
<form id="Form1" runat="server" onsubmit="Q++; if(Q==1){return true;} else { return false;}">
This seems to be working and please forward your comments.
Arun
http://www.velocityreviews.com/forums/t117900-asp-net-multiple-postback-issue.html

Resources