Strangely Query String is disappeared on live server - c#

Maybe this is a very normal behaviour or I am missing something very basic. I have a page named Default.aspx and it is set to Default page for my web application. On this page there is a dropdownlist for categories and when I select any value then response.redirect is called for the same page and category id is passed as a query string. Now everything work just fine when I test the application locally. When I publish the website on the server and call the website with url www.mywebsite.com then the default page is displayed but page name is not displayed. I have no issue with it but without the page name my response.redirect stops working. So just to summarize all this in following lines,
www.mysite.com
// On Selected Index Changed
Response.Redirect("~/Default.aspx?catId="+ ddlCategory.SelectedItem.Value);
The Url should be for first category
www.mysite.com/Default.aspx?catId=1
but it is not changing and on postback www.mysite.com is displayed.
However if in the address bar I have,
www.mysite.com/Default.aspx
and now if I change the selected index of drop down then it works fine and the url becomes,
www.mysite.com/Default.aspx?catId=1
Now I don't know whether this question was asked already because I don't even know what the issue is and what should I search.
Update:
Now this is reproduced in the local system also. It seems that when the page name Default.aspx is not present in the address bar with url then SelectedIndexChanged is not called. If Default.aspx is in the address bar then SelectedIndexChanged is fired.

Well I am still unable to find the exact reason for the behaviour that I have mentioned in my question but I have applied a workaround. I am now not calling the SelectedIndexChange event from code behind, instead I am using Javascript to redirect to the same page with query string.
<script type="text/javascript">
function CategoryChanged() {
var ddlReport = document.getElementById("<%=ddlCategory.ClientID%>");
window.location = 'Default.aspx?catId=' + ddlCategory.value;
}
</script>
And called this on onchange of my dropdownlist,
onchange="CategoryChanged()"
Beside this solution I would love to know that why the code behind event was not called when page name is not mentioned in the url. So if anyone has any idea do share their thoughts.

Related

blazor not changing the page when clicking on a link

I am migrating my personal blog to Blazor, and I have a problem. I was developing the "next post" functionality and blazor (or the browser) is not redirecting the user when a link is clicked. the post are "the same page" under the next route #page "/post/{Url}
For example the user is in domain.com/post/foo and in that site there is a link to domain.com/post/bar.
It is a simple link, like the next:
<a href="post/bar" title="#Post.Title">
#Post.Title
</a>
When the user clicks on the link the url for the browser changes, and the location of the page moves to the top, but the page content is not changing.
I noticed that this behaviour is happening when I click from a post page into another, but is not happening from the "index" of the site (/) or when I click the tags on the post, which links to domain.com/tags/{tag}.
one thing to notice is that if I select the url in the browser and click enter or refresh the page it actually goes to the page i clicked on, in this case domain.com/post/bar
My question is, is this actually expected behavior or is it a bug? if it is expected behaviour, is there any way of making the url to actually go to the clicked url and not stay in the same page.
I am using net5.0 if that matters.
Thanks.
As an add on to #enet's answer, you're probably fetching the post referenced by the Url property in OnInitialized/OnInitializedAsync. See the last long paragraph in #enet's answer.
One way to address this is:
place the code to load data in a separate method say LoadDataAsync
in SetParameters/SetParametersAsync detect if the data reference - in your case Url - has changed in , and if so call LoadDataAsync.
The key here is understand component lifecycle and getting the code in the right place.
Put breakpoints in on OnInitialized and SetParameters and watch when they get hit when you load and do navigation.
when I click from a post page into another
post in domain.com/post/foo and domain.com/post/bar is definitely not a page but a literal path segment.
I've created a routable component named Foo:
Foo.razor
#page "/post/foo"
#code {
}
Foo is a routable component; that is, it is a page, and can be accessed by typing the url in the address bar of your browser, using an anchor element or the NavigationManager. You may embed it in a parent component as well.
post is, as I've said above, a literal path segment
But if you insist that post is actually a component page, then I guess it may look something like this:
Post.razor
#page "/post"
#page "/post/{Param}"
<a href="post/bar" title="Title">
Title
</a>
<div>#Param</div>
#code {
[Parameter]
public string Param {get;set;}
}
Now, when you type in the address bar a url like this:
https://localhost:<port-number>/post
You'll be navigated to the post routable component (page)
If you click on the anchor element, the url in the address bar will change to https://localhost:<port-number>/post/bar
bar is not a component; it is a parameter. The address bar changes, but you seem to be in the same post component, the data or content, however, do changes...
Note that when you click on the anchor element, you are being navigated to
a new Url ("post/bar"), but rendering engine does not create a new instance of the Post component in order to render the page, but instead it treats it as the same page with changed parameters. Thus it looks like no navigation has taken place, and nothing has changed, except the url in the address bar. I'm not claiming that your issue is the same, but it may stem from similar code usage.
Note that since Blazor does not create a new component instance, but uses the existing one, the OnInitialized(Async) pairs can only run once... So you'll have to use the SetParametersAsync method (" on initializedAsync is getting the "nextPost" information from the backend, but its just a plain http cal")
All the above was intended to ask you to do the simplest thing and provide the route templates........
Is bar a component?
Is foo a component?
Answer withdrawn as it breaks some component parameter recommendations by ASPNetCore Team - see https://github.com/dotnet/aspnetcore/issues/24599

Invalid postback or callback argument on dropdowns

I have this two radio buttons
on click of ship to above address Left dropdowns values will be gone to right one
All working fine but when i click on button submit of this page then I have this error
Invalid postback or callback argument. Event validation is enabled using 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.
Obviously i know if i do eventvalidation='false' then it will work but is there anything else that can solve this problem with eventvalidation='true'?
For a moment i think that binding of dropdown is wrong so i tried diff codes in javscript but same result i am getting from it my javscript code looks like
$("#ctl00_ContentPlaceHolder1_ddlshippingPostcode").html($("#ctl00_ContentPlaceHolder1_ddlpostcode").html());
$("#ctl00_ContentPlaceHolder1_ddlshippingState").html($("#ctl00_ContentPlaceHolder1_ddlstate").html());
Also i tried
document.getElementById('ctl00_ContentPlaceHolder1_ddlshippingPostcode').innerHTML=document.getElementById('ctl00_ContentPlaceHolder1_ddlshippingPostcode').innerHTML+document.getElementById('ctl00_ContentPlaceHolder1_ddlpostcode').innerHTML;
document.getElementById('ctl00_ContentPlaceHolder1_ddlshippingState').innerHTML=document.getElementById('ctl00_ContentPlaceHolder1_ddlshippingState').innerHTML+document.getElementById('ctl00_ContentPlaceHolder1_ddlstate').innerHTML;
Any help would be appreciated?
One thing to note that if i don't bind dropdowns with javascript then that error does not appears
Thanks to #abhitalks ya i have to go for serverside code because of the prepopulated code done by the dropdowns and i don't want to do server side coding so now i have done like this
at page load time i have binded right side drops also like this
So when user clicks on Ship to above address then i just have to select the drops like this
$("#ctl00_ContentPlaceHolder1_ddlshippingPostcode").val($("#ctl00_ContentPlaceHolder1_ddlpostcode").val());
$("#ctl00_ContentPlaceHolder1_ddlshippingState").val($("#ctl00_ContentPlaceHolder1_ddlstate").val());
And it works great with event validation=true
So after clicking i just play with selection of dropdowns like this when clicked on above address will be look like

ASP.NET Page Cycle Confusion

If I have a button on my ASP.NET page which will take you to another page but that page will do something and then will send user back using
Uri uu= Request.UrlReferrer;
if (uu!= null)
Response.Redirect(uu.ToString());
Now Which page event can I use so that when other pages displays I can display a message box.
In short I am running my custom code in a "aspx" page where user is directed on button click, and then after custom code I am sending user back to old page, but it happens so quickly that user doesn't realize that he went on another page, now I want to display a message box after redirect on same page user started from, what to do :S !
More Information
EDIT
Sorry guys but I can't make changes to ASP page where button is at all
:(
I'm a bit unsure about how the Request.UrlReferrer gets set. I think it's a browser implementation detail. So I wouldn't trust on that.
I would go for something like
A.aspx -> Redirects to -> B.aspx
B.aspx -> Redirects to -> B.aspx?message=1
And check if message=1 is set.
But if you want to use the Request.UrlReferrer it should be accessible on Page_Load
If you use it this way, it'll never appear to the client.
Maybe try redirecting back using javascript with a delay so user can be informed
The best thing to do it's add a flag to the redirected page so you can show something special when the flag is turned on
Uri uu= Request.UrlReferrer;
if (uu!= null)
Response.Redirect(uu.ToString() + "?Message=DataHasChanged");
and then in the ASP page
<% if (Request.QueryString["Message"] == "DataHasChanged") { %>
<div class="alert">The data has changed. Please review it or whatever</div>
<% } %>

In url rewriting, why is the postback giving the wrong url?

I am experimenting with URL Rewriting. The first time it displays with the correct url. After perfroming any event handling, the form posts back, and then it has wrong url.
Like the page url is http://devweb.tsgdomain.com/nphnewdemo/Enewsletter/68 and when i click url button then it gives wrong url http://devweb.tsgdomain.com/nphnewdemo/Enewsletter/popup.aspx?name=dev-test-please-review-it insted of this url http://devweb.tsgdomain.com/nphnewdemo/popup.aspx?name=dev-test-please-review-it.
Please suggest some answers to why this is happening (and how I can make this work correctly).
This is happens because the form is rendering using the actual URL (and not what user see).
If you like to change that you can be rewriting the form attribute making a global handler of the form.
Here is a full solution that is tested and working.
http://www.koders.com/csharp/fid39B3A4A2AD871AA78E7E5D8643A076EF4352CDF9.aspx
In the aboce code the line that make the change is the
value = Context.Request.RawUrl;

user control event handler lost on postback

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.

Categories