So I have a slightly unorthodox application type.
I have an aspx page called AddNewBlog.aspx. This page generates XML data from database queries and it include the file AddNewBlogXSL.aspx which is an xsl style sheet.
The effect is that the AddNewBlog XML data is transformed by AddNewBlogXSL on the client side into XHTML.
So although the requested page is AddNewBlog.aspx, the layouts and controls and forms are on AddNewBlogXSL.aspx since it contains all the layout and formatting.
When on AddNewBlogXSL.aspx I do an asp:button it tries to post back to AddNewBlogXSL.aspx as is understandable.
The problem is that page is an xslt stylesheet not a webpage.. I need it to post back to AddNewBlog.aspx as this is the proper page which includes AddNewBlogXSL.aspx
The only thing I seem to be able to do is allow the default behaviour which is to submit to AddNewBlogXSL.aspx, process the page, and redirect them to the proper page AddNewBlog.aspx but then it makes it hard to handle error messages and such since I have no control over AddNewBlog.aspx after I have simply redirected to it from AddNewBlogXSL.aspx
Any ideas at all?
You are looking for PostBackUrl property.
<asp:button id="Button2"
text="Post value to another page"
postbackurl="~/Path/To/AddNewBlog.aspx"
runat="Server">
</asp:button>
EDIT:
To address your comment, IsPostBack will not be true in this scenario because it isn't a postback, it's just a post to another page. You have to access the values via the Page.PreviousPage property as outlined in the MSDN article I listed.
During a cross-page postback, the contents of the source page's controls are posted to the target page, and the browser executes an HTTP POST operation (not a GET operation). However, in the target page, the IsPostBack property is false immediately after a cross-page post. Although the behavior is that of a POST, the cross-posting is not a postback to the target page. Therefore, IsPostBack is set to false and the target page can go through its first-time code.
Also per MSDN, you would check the PreviousPage.IsCrossPagePostBack property instead of the Page.IsPostBackProperty
if(PreviousPage.IsCrossPagePostBack == true)
{
//Get values from PreviousPage
text = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
}
Cross Page Posting Details
I went ahead and wrote a little test harness (aka, I took the example off the MSDN page, :-0 )to verify and results are as follows when cross page posting:
It's not an ideal situation and it kludgey to access your values as listed, but for the model you have designed, it's the best I can think of.
In addition to the above answer, Can you please confirm that the "AutoEventWireUp" is false in this page. If so, override the page load method in this case.
Related
I have two pages in ASP.NET 3.5 and I need to access/read the web controls values from the first page but on the second page. The second page is being displayed with a single link, there is not a post event or something like that.
I guess I should use ViewState but it looks so complicated for this task so please let me know a better way to achieve this.
P.S I'm using C# and Visual Studio 2010
If I understand correctly you have two .aspx pages and you want one page to share information with the other page. Does the first page link to the second page?
I ask because there are a couple of approaches you could take. You could add parameters to a query string in the link to the second page with the information you are trying to send. You could also use the session to temporarily store the information.
For example:
<asp:HyperLink NavigateUrl="www.<yoursite>.com/firstpage.aspx?eggs=1&bacon=yum" Text="Awesome Site" runat="server" />
In the second page you would have this in the codebehind in the Page_Load
string eggs = Request.QueryString["eggs"];
string bacon = Request.QueryString["bacon"];
Now you have the value from page one available in page two.
Another approach might be to use the Session like so:
Page one:
Session["bacon"] = "Yum";
Page two:
string bacon = (string)Session["bacon"];
However, I would advise against overusing session to pass information between pages.
Quick & "Dirty": A session variable which holds the info to pass.
On the first page:
Session["ValueToPassToOtherControl"] = "The value";
On the second page:
var value = Session["ValueToPassToOtherControl"];
Elegant: You need to manage your state in any way (via a static manager whose function is to store and retrieve that info, but that will be also variables). Problem is HTTP is stateless. So you need to bypass this limitation via some kind of storing and retrieving of the data.
You suggested the use of ViewState but forget it, ViewState is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks which isn't what's happening on your scenario.
There is a better way that using the QueryString jugglery and Session values.
You could just use the previous page property that is set during cross page posting.
Use an asp link button:
<asp:LinkButton runat="server" id="myLink"
NavigateUrl="~/Page2.aspx"
target="_blank" Text="Go to page 2"></asp:LinkButton>
Then on Page2.aspx.cs:
Get the values from the Page.PreviousPage as follows:
TextBox txtUser = (TextBox)Page.PreviousPage.FindControl("txtUser");
TextBox txtSomeValue = (TextBox)Page.PreviousPage.FindControl("txtSomeValue");
Use these as you require in your second page.
I'm working on a web form which works in a following way.
Read email template from database
Display email template on a web form in HTML format
User adds additional information to the web form and clicks on submit button
Before I get to a method which will process that request, I get A potentially dangerous Request.Form
I have looked at few articles that advise using .Net 2.0 in one of the web.config sections - that didn't work. I have set requestValidation = "false" for that page and it didn't work either.
My gut feeling is that I'm doing something fundamentally wrong...
HTML template is stored as VarChar(4000) in a database.
I have tried encoding text in a method before I send an email, but that didn't work either because the web form never got to executing that method.
What other options do I have? I have tried storing plain text in database, but then I have issue of tabs and returns etc.
Thank you
The remedy is in two parts and you MUST action both:
To disable request validation on a page add the following directive to the existing "page" directive in the file (you will need to switch to the HTML view for this):
ValidateRequest="false"
for example if you already have:
<%# Page Language="vb" AutoEventWireup="false"
Codebehind="MyForm.aspx.vb"
Inherits="Proj.MyForm"%>
then this should become:
<%# Page Language="vb" AutoEventWireup="false"
Codebehind="MyForm.aspx.vb"
Inherits="Proj.MyForm"
ValidateRequest="false"%>
In later versions of Visual Studio the value of this property is available via the page properties, so simply set "ValidateRequest" to "False". Either method of setting this achieves the same result.
Alternately, you can globally turn request validation off (but in which case be sure to implement item two below). To globally turn request validation off add the following to your web.config file:
<pages validateRequest="false" />
From: http://www.cryer.co.uk/brian/mswinswdev/ms_vbnet_server_error_potentially_dangerous.htm
As a first security lesson, never trust user input,so if you setting request validation to false then always HTML encode the input.
In basic either use: OnClientClick on submit and replace, < with & lt; and > with & gt; (no space with & and gt/lt)
or on submit method, use Server.HTMLEncode(inputtext)..or however you process it.
I have a page that requires the user to go through several steps, however step is performed on the same ASPX page with different panels being displayed.
However this is a requirement that each step has a different URL, this could be a simple as a query string parameter, for example:
Step 1:
/member/signup.aspx?step=1
Step 2:
/member/signup.aspx?step=2
Step 3:
/member/signup.aspx?step=3
However I don't want to have to redirect the user to the new URL each time they continue to the next step, this would involve a lot of redirecting and also a switch statement on the page load to work out which step the user is on.
It would be better if I could alter the URL that is displayed to the user when the original request is sent back to the user, i.e. the user click "next" on step 1 the page then does some processing and then alters response so that the user then sees the step 2 URL but without any redirection.
Any ideas would be greatly appreciated.
Could you convert your Panels into steps in a Wizard control?
It would be a little more complicated than you probably want, but you could achieve this effect with the PostBackUrl property of the submitting button. I'm assuming each panel has its own "submit" button, and they could all use this property to "advance" the process. The drawback is that in order to get to submitted controls, you'd need to use the Page.PreviousPage property in order to access any controls and their values.
You could programmatically alter the PostbackUrl property of your 'Next' button on each Page_Load, based on the query string value. This is a bit strange though, as you wouldn't be able to use a standard event handler for the button click, and you'd have to use the PreviousPage property of the Page to get the data from the previous tab.
I'd say challenge this requirement. Why would anyone need to jump into the middle step? If it's a case of displaying the progress to the user, do this on the page, not in the URL.
You require that each step has different URL, than Response.Redirect is the only option. As you want to avoid the redirection, you can use IFrame but IFrame URL is not visible to user on his browser. I think redirect option is ugly(for both SERVER and CLIENT) as in this case, you first post on the page and than get that page. The best solution is POST BACK with some varible tracking step.
You could implement a form or url rewriting so that your urls end up being
/member/signup/step1/
/member/signup/step2/
/member/signup/step3/
To do this use the
HttpContext.RewritePath method which means you can rewrite /member/signup/step1/ to /member/signup.aspx?step=1 for example. See an example here.
I would also use the PRG (post request get) pattern so that each next link posts the form data of that step to the session then redirects the user top the correct next url. this will ensure that the user can navigate back and forth through the steps safely and also the url will remain intact in all your posts.
Check out server.transfer
I have a menu usercontrol called LeftMenu that has a bulletedlist of linkitems. It's on the ascx page as such:
<asp:BulletedList ID="PublisherList" DisplayMode="LinkButton" OnClick="PublisherList_Click" cssClass="Menu" runat="server"></asp:BulletedList>
I databind the list in the page_load under if(!isPostBack)
I'm having an issue on a page that loads the control. When the page first loads, the event handler fires. However, when the page posts back it no longer fires and in IE8, when I'm debugging, I get "Microsoft JScript runtime error: Object expected" in Visual Studio pointing at "__doPostBack('LeftMenu$PublisherList','0')." In FF I don't get the error, but nothing happens. I'm not loading the control dynamically, it's loaded on the aspx page using:
<%# Register TagPrefix="Standards" TagName="LeftMenu" Src="LeftMenu.ascx" %>
<Standards:LeftMenu ID="LeftMenu" runat="server"/>
Any ideas of where I'm losing the event handler?
I just realized this is happening on another user control I have as well. A text box and a button and I'm using the default button to make sure pressing the enter key uses that button. .Net converts that in the html to:
<div id="SearchBarInclude_SearchBar" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'SearchBarInclude_QuickSearchButton')">
so as soon as i enter a key in the box I get a javascript error at the line saying "object expected." It seems like the two issues are related.
Edit Again: I think I need to clarify. It's not that I'm clicking on the menu item and it can't find the selected item on postback. I have this search page with the left navigation on it and then the main content of the page is something that causes a postback. Everything is fine with this postback. Once that page has been posted back, now if I click on the bulleted list in the left navigation I get a javascript error and it fails. The page_init for the LeftMenu control is never called.
It sounds like you might be losing the click because you are not DataBinding the list on PostBack. Therefore, the post back is trying to refer to a control (a specific bulleted list item) that does not exist.
You should try binding the list again on PostBack just to see if that fixes your issue. BUT, what should REALLY happen is that the LeftMenu and the BulletedList should store their information into ViewState so that you can ensure that the data that was shown to the user on their initial page load is the same data that the PostBack is processing and working with.
If you have EnableViewState=true for your UserControl and all controls within it, everything should work fine. With ViewState enabled, ASP will reinflate your controls from ViewState after Init has fired. This means that the postback event arg (which points to an index in your control list) will still find the control in that list position. Otherwise the list is empty on postback.
However, ViewState is the work of the devil and was designed simply to foster the illusion that you are working in a stateful environment. It is okay to use it for small amounts of data but typically not advisable for templated controls like repeaters and lists because you have no idea how much data is going to be created in ViewState.
If you are dealing with static, or relatively static data, store it in the application cache and rebind your lists in Page.Init every time (note that it has to be in Init because post-init is when ASP rebinds from ViewState; if you get in there first, your data will be used instead).
If you are dealing with volatile data, you have a problem because the data you rebind must be exactly the same as the original page request, otherwise the postback events will be firing against the wrong rows. In that case you need to either store your initial data in Session or you simply store the list of rows ids (in a hidden variable or Session) and you recreate the data to bind against from the ids each time.
An even better solution is to not use postback events at all. Try to turn all your events into GETs that have an ID on the query string. You can still create the list using binding the first time through the page (as you are currently doing), and you can even GET the same page with a new ID.
If you need to keep state on the same page but need to respond to the user changing a radio button selection (or something else), think about using Ajax calls to update the screen. You also do that with an ID that you pass to the Ajax call.
In general, the more you move from using stateful ASP, the lighter and more responsive your pages will become. You will also be in a better position to move to stateless MVC if necessary. You will also save lots of time lost to debugging obscure problems because ViewState is not available when you need it to be.
The best analysis of ViewState I've read is in the link below. If you fully understand how it works, you can continue to use it without necessarily incurring the costs.
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx
It's possible that this might be javascript related, and that a script that is loading earlier in the page is throwing an error and causing the page to not be loaded properly.
Are your usercontrols loading any javascript onto the page? Can you check for javascript errors on the initial load of the page?
I moved the code into an existing project we have and for some strange reason, I stopped getting the javascript errors and instead got:
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
I haven't quite figured out where I'm supposed to put the register event validation with a user control, but in the mean time I just set enableeventvalidation=false and it seems to work now.
It looks like the doPostBack function is missing since its arguments are literals so they couldn't be the cause. Is that one of your own functions or did you mean to call the ASP __doPostBack function?
Have a look at the Firefox error console or allow script debugging in IE and see exactly what object can't be found. Even better, download Firebug and debug it.
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.
I am using jQuery to simulate a popup, where the user will select a series of filters, which I hope to use to rebind a ListView in the original window.
The "popup" is opened via an ajax request and the content is actually a diferent aspx file (the rendered output is injected into a div that acts as the popup).
I have another ListView in this popup, and it has pagination.
My problem is that since the popup is in reality html content inside a div in the same page, when I try to paginate, the whole page postbacks and is replaced with the aspx that has the filters.
How can I fix this?
I tried using an update panel to contain the ListView but it didn't work.
$("div.yourthingie").hide();
Will hide the part you want to show :) Instead of generating the popup on the fly, leave a small part already made, and hide it in the begining, when you need to show, unhide and add the information you need to.
Hope it helps
Either get rid of the HTML "crust" and just produce the <div> with its contents, or use an IFRAME.
First, let's think through what is happening. When you submit the original page, you are taking a "normal" Request/Response trip to get the code. On the page is a JQuery AJAX bit that fires off what is essentially a modal dialog. The desired effect is the user plays with the new page until they have figured out their filters and submits back. The problem is this "modal page" loses information when someone paginates.
The solution to this is fairly simple, in theory. You have to store the "filters" in the popped up page so they can be resent, along with pagination information. OR you have to cache the result set while the user paginates.
What I would do to solve this is create a static page that has the "filters" in place and work out the AJAX kinks separate from having the page post back to a parent page. Once you have all of the AJAX bits working properly, I would then link it into the popup routine and make sure the pagination is still non-problematic. THe final problem is creating a JavaScript routine that sends back to the parent page and allows the parent page to send its JQuery bits back to the server.
I am not sure about the HTML DIV part of the equation and I think you can solve the problem without this solution. In fact, I believe you can make the "modal popup" page without invoking AJAX, if it is possible to either a) submit the filters to apply via the querystring or b) fake a form submit to the second page. The query string is an easier option, but it exposes some info. Faking a form submit is not that difficult, overall, but could be problematic with a popup.
I am just firing off some ideas, but I hope it spurs something for you.