Postback with Modified Query String from Dropdown in ASP.NET - 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));

Related

Read hidden field values from another page

I am developing a website using ASP.net.
In my home page I have 14 tree view controls. They were placed under Jquery tabs. So when a user click a tab it only appears one treeview. So in tree node changed event currently what I am doing is passing the values from query string to another page. this query string doesnt have any sensitive data. I have to pass what is the selected Tab Id and selected tree node Id.
Response.Redirect(String.Format("~/Display.aspx?tab=1&type={0}",treeview1.SelectedValue), true);
But you know URL is ugly. I dont want to use Friendly URL thing now.
So what I did was I put 2 hidden fields values in my home page and I set them when I click the tree node.
So then from the source page I used this code to acess this.
if(Page.PreviousPage!=null)
{
string tab= Page.PreviousPage.FindControl("hftab").UniqueID;
string Type= Page.PreviousPage.FindControl("hfType").UniqueID;
}
But Page.PreviousPage always return NULL. So how to solve this probelem without using sessions and query string. I just want to pass two non sensitive data behind the scenes.
IF this is about Cross page postback thing How to do this cross page post back in node change event? Is it ok to do a Cross page post back for to get only 2 values that I needed?
The method you are trying is only possible with "Cross page posting" mechanism. When you set PostbackUrl property of a server control like button, and set the PreviousPage property of Page directive on destination page; then only you will get Page.PreviousPage values.
Here are some reference:
1. http://www.codeproject.com/Tips/604553/Postback-and-Cross-Page-Posting-in-ASP-NET
2. http://www.aspdotnet-suresh.com/2010/05/cross-page-post-backing-in-net.html

Passing values that aren't related to inputs using MVC?

I have page where users can select from one or more images. When they are done I would like them to navigate to the next page and what is displayed would be based on the selection from the previous page.
"Selecting" just means that they click the image and it has a CSS class added to it. When they click the link to navigate to the next page I'd like to collect the images that have been selected and pass that information along using either TempData or Session.
In most of the examples I have seen either inputs or the query string is used to pass information from the View to the Controller. How can I pass which elements have a particular class to my controller when a link is clicked?
If you're using a link click, I'd probably just append the selected images to the query string. I'm assuming you don't mind exposing this query string to end users.
I'm sure that's probably not the answer you were looking for. But as you stated I think you're only to legitimate options are passing the values through the query string or using hidden inputs and posting the page to your action by intercepting the link click event.
You said you do not want to post back to servers. You cannot access TempData or Session without posting back to server, so they are out of scope.
You only have client side option, so you want to collect a user's selected items in array.
Once the user clicks to Next Page, you create a query string like this ?ids=1-2-3-4 and retrieve those value at next page.
Other thoughts: Long URL likes this is a bit ugly, and URL has maximum length limit depending on browser. If I'm you, I'll post back to server to collect the selected values. Then use TempData (or some persistent storage).

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

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

Pass a value and reload User Control from Javascript

I have a User control (because I use the same in other page, so I thought I should reuse code and not double my work), but in this page I show a list of companies and each one has a company number, I need to pass this company number to that User Control and it has to reload using that passed company number.
How can I accomplish this?
what I have so far:
alt text http://www.balexandre.com/temp/2009-09-17_0917.png
the Show company structure link is made of
<a href="javascript:showStruct('112:201334607','5564967221');"
class="showStructLink">Show company structure</a>
the showStruct method is written like
function showStruct(pid, cnr) {
if (_showStrut == 0)
return;
// fancy stuff to be more apealing visually
$("#tdSearch").removeClass("tabTitleUp01").addClass("tabTitleDownUp01");
$("#tdStruct").removeClass("tabTitleDownUp02").addClass("tabTitleUp02");
$("#srtr1").hide();
$("#srtr2").hide();
$("#sttr1").show();
// enable Search Results tab to be clicked in order to get back
$("#tdSearch")
.addClass("pointer")
.bind("click", function() { hideStructure(); });
// pass the company number and reload wcCompanyStruture web user control
// __doPostBack('RefreshWebUserControl', cnr);
}
I can make a simple aspx page with the control inside and from jQuery invoke $.get() to run and populate the control correctly, but I really want to learn how to do this properly, using the ASP.NET AJAX Method to send a number and call RefreshData on it
using code-behind it is easy to refresh the user control, just invoking
wcCompanyStruture.RefreshData("companyNumberHere");
what do I need to do in my User Control side and well in the showStruct method to create this behavior?
All help is appreciated, Thank you.
I know this is not the answer to you question but I think you may be asking the wrong question.
It looks to me as if you have a search result+details view scenario that you are going about the wrong way.
When you click "Show Company structure" you want to see the details on the second tab right? If this is the case then the tab approach would be confusing to the user, it would be better with a modal popup that shows the details. No postback just AJAX load a page with the details into a modal popup window.
This is very easy with JQuery using the dialog widget in JQueryUI and the AJAX load function $('#SomeDiv').load('details.aspx?id='+companyid);
http://docs.jquery.com/Ajax/load#urldatacallback
It would give a much better user experience and it is surprisingly simple to code.
I hope this helps.
You can use a LinkButton for each "Show Company Structure" link, and set the CommandArgument property with the corresponding company id. The LinkButton will cause a postback.
A second solution would be to use a hidden variable : <input type="hidden" id="hiddenCompanyNumber"> and set it's value in the showStruct method. You can then call __doPostBack(), for which you need a control upon which to postback I think.
All in all, I think the first solution is less hacky.
You can find it here
http://codeclimber.net.nz/archive/2007/06/26/how-to-refresh-an-updatepanel-from-javascript.aspx
don't worry about the article title it has what you need Just do the four steps and you are ready to go.

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.

Resources