I'm fairly new to ASP.NET, I've been reading a few questions related to this but I'm still unable to figure out what's wrong with my code, I have a default.aspx page with a menu on top created using a list (ul and li items) and putting the <a href=""> tag to create the links to other pages but after following a link to another page, the Page_Load event fires before leaving the page, I understand this would be the expected behavior with Response.Redirect, but I don't know how to avoid this using tags (if possible), this is the markup I'm using for the Default.aspx page:
<ul id="lista">
<li><strong>Inicio</strong></li>
<li><strong>Item</strong></li>
<li><strong>IK</strong></li>
<li><strong>Acerca de</strong></li>
</ul>
And this is the code behind I have for Page_Load:
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
ExcelUtility excel = new ExcelUtility();
dtDefault = excel.LeerExcel();
gridResults.DataSource = dtDefault;
gridResults.DataBind();
gridResults.VirtualItemCount = dtDefault.Rows.Count;
}
}
Basically, what I want to do is to follow the link to some other page without loading the default page before leaving, hope I make myself clear!
Edit: The root cause of this was having the default <form runat="server"> tag at the beginning of the body section, this was causing the Page_Load event firing again in the same page once the links were being clicked, placing the hyperlinks outside of the form tag did the trick.
Your HTML code should be inside some HTML tag or custom ASP control which contains the attribute runat="server". This is supposed to fire a PostBack request to the server.
Related
How to you code an <a href="... tag in ASPX to call a simple code behind function?
I have inherited a bit of code. I did not write this originally but I am trying to modify it.
In the steppayment.aspx file there are lots of "<a href..." tags that target either a whole URL or another aspx file.
But what if I only want to call a function in the code-behind, steppayment.aspx.cs?
In the aspx file, steppayment.aspx, I have this line of code:
<u><b><a href="fsModifyVisualContentonPaypal();" >Click here</a></b></u> now to open the PayPal payment window.
In the code behind, steppayment.aspx.cs, I have this line of code:
protected void fsModifyVisualContentonPaypal()
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
I have break points in this function. It never gets here. When the user clicks on the "click here" it throws an error.
Use a LinkButton control instead of a basic HTML anchor tag
<asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server" Text="Click here" />
To call client side methods like javascript you would use OnClientClick. You'll want to check out the documentation for LinkButton on MSDN
If it you want it to work on postback, try an ASP.NET LinkButton control.
This is from memory, but it would be something like this:
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
If you want it to work without a postback, that gets you into either Ajax territory or plain JavaScript. (Or, you might look up the ASP.NET UpdatePanel.)
All of this is assuming that you're using ASP.NET WebForms. If you're using MVC, that's another topic.
Both answers would work. You need to change the event method signature as well like this:
protected void fsModifyVisualContentonPaypal(object sender, EventArgs e)
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
And your link button should look like this ( as suggesested by both answers):
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
I am needing to use the same form for displaying multiple things and I realize that when I add links like:
A
it has the same form and web address, but with a #A at the end of the address.I thought I could use this for displaying multiple things on the same form. My idea is to have C# code in the page_load method to detect what the web address is and use a conatins method for the url string and detect if there is #A to change the content of the form. Here is an example:
C# code:
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("#A"))
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
asp.net code:
A
<div ID="div1" runat="server">
content 1
</div>
<div ID="div2" runat="server">
content 2
</div>
I have tried to put the Page_Load method in a script tag, but still didn't work. I guess since the url is different the cs code is not valid? I know it goes through the page_load method once, before I click on the link. Also I do use a method that gives me the controls of div1 and div2, so that is not the problem. I thank everyone in advance for your help! Also if my way is not the way to do the job then please tell me any way possible to achieve what I am trying to do.
edit: I can't use a button to replace a link... maybe a asp:hyperlink?
That's an HTML hyperlink you're using and it won't cause a postback thus page_load will never get called when you click it.
I would suggest if you want to show an hide divs that you use client side JavaScript. Alternatively you could (for example) use an asp.net button control which will cause a postback.
I would suggest scrapping the anchor with an href approach in favor of this:
Use the ASP.NET server controls, along with their click event handlers to manage the visibility of controls on your page.
In your Page_Load, make it so the page has an initial state of showing controls, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
Now instead of an anchor tag, you can use an ASP.NET Button or LinkButton to cause a postback to the server, like this:
<asp:Button id="Button1"
Text="Click here to change page to B"
OnClick="Button1_Click"
runat="server"/>
Now you have the event handler code which would change the visibility of controls, like this:
protected void Button1_Click(Object sender, EventArgs e)
{
div1.Visible = true; //content 1
div2.visible = false; //content 2
}
I have a fairly simple page with a set of jQuery tabs, the content of some is called via ajax. I also have a search box in the masterpage in my header.
When I open the tabbed page the search box works fine. However once I have clicked on one of the ajax tabs the search box fails to work with an "Invalid Viewstate" yellow screen of death.
I believe this is because the ajax page is replacing the __VIEWSTATE hidden input with its own.
How can I stop this behaviour?
UPDATE: I have noticed that the YSOD only appears in IE and Chrome, Firefox doesn't seem to have the same issue. Although how the browser influences the ViewState, I'm not sure.
UPDATE: I've put a cut down version of the site that shows the issue here: http://dropbox.com/s/7wqgjqqdorgp958/stackoverflow.zip
The reason of such behavior is that you getting content of the ajaxTab.aspx page asynchronously and paste it into another aspx page. So you getting two instances of hidden fields with __VIEWSTATE name and when page posted back to server theirs values are mixing (might depends on how browser process multiple controls with same name on submit). To resolve this you can put second tab's content into a frame:
<div id="tabs">
<ul>
<li>Default Tab</li>
<li>ajax Content</li>
</ul>
<div id="tabs-1">
<p>
To replicate the error:
<ul>
<li>First use the search box top right to search to prove that code is ok</li>
<li>Then click the second ajax tab, and search again.</li>
<li>N.B. Chrome / IE give a state error, Firefox does not</li>
</ul>
</p>
</div>
<iframe id="tabs-2" src="ajaxTab.aspx" style="width:100%;" ></iframe>
</div>
Also, I'm not sure but this seems like error in the Web_UserControls_search control. In my opinion, NavBarSearchItemNoSearchItem_OnClick method must be refactored as below:
protected void NavBarSearchItemNoSearchItem_OnClick(object sender, EventArgs e)
{
var searchFieldTbx = NavBarSearchItemNo;
var navBarSearchCatHiddenField = NavBarSearchCatHiddenField;
var term = searchFieldTbx != null ? searchFieldTbx.Text : "";
if (term.Length > 0) //There is actually something in the input box we can work with
{
//Response.Redirect(Url.GetUrl("SearchResults", term));
Response.Redirect(ResolveClientUrl("~/Web/SearchResults.aspx?term=" + term + "&cat=" + navBarSearchCatHiddenField.Value));
}
}
Draw attention that we resolving client url when redirecting to search results page and instead of navBarSearchCatHiddenField use navBarSearchCatHiddenField.Value as cat parameter.
I guess that you use AJAX to fill the content of the tab. So in this case, content of your tab will be replaced by the new one from ajax and certainly _VIEWSTATE will be replaced. At server, do you use data from ViewState? In the "static tabs", you should prevent them auto reload by using cache:true
Your issue is that with your ajax call you bring in a complete ASPX page. Including the Form tag and its Viewstate. If you remove the Form tag from ajaxTab.aspx you will see everything works fine. asp.net does not know how to handle two Form tags in one page. Same goes for hidden Viewstate fields. You cannot bring in a full aspx page via ajax. Just bring in the content Div you want to display and you`ll be good to go.
I have a master page and all of my pages are inheriting it.
For formatting, I thought to place the content that differs from one page to another in a ContentPlaceHolder.
Now, how can I insert everything into that? Since I am planning to populate the ContentPlaceHolder with stuff from a database I suppose I will have to do it programmatically.
How can I add controls to ContentPlace Holder?
I checked other answers, but I cannot access it by its ID.
Should I use multiple ContentPlaceHolders from the beginning? Let's say I want to put movies. Should there be only one with all the images and descriptions and ratings, ore one ContentPlaceHolder for each thing?
I am opened to other solutions, as I have no experience with ASP.
Old question... but I just ran into this issue and this was the #1 post that kept coming up on Google, so figure I'd add my answer since the others didn't work in my case.
Here is how I did it when a regular <asp:Content wouldn't work (though in normal use, the answer #JayC is how you do it):
MasterPage has this ContentPlaceHolder:
<asp:ContentPlaceHolder ID="ScriptsPlace" runat="server"></asp:ContentPlaceHolder>
Had to dynamically add some JavaScript from a User Control. Trying to use the ContentPlaceHolder directly gives this error:
Parser Error Message: Content controls have to be top-level controls
in a content page or a nested master page that references a master
page.
So I wanted to add the script from the code-behind. Here is the Page Load for the .ascx file:
protected void Page_Load(object sender, EventArgs e)
{
ContentPlaceHolder c = Page.Master.FindControl("ScriptsPlace") as ContentPlaceHolder;
if (c != null)
{
LiteralControl l = new LiteralControl();
l.Text="<script type=\"text/javascript\">$(document).ready(function () {js stuff;});</script>";
c.Controls.Add(l);
}
}
UPDATE: So it turns out I had to use this in more places than I expected, and ended up using a way that was much more flexible / readable. In the user control itself, I just wrapped the javascript and anything else that needed to be moved with a regular div.
<div id="_jsDiv" runat="server">
$(document).ready(function() {
//js stuff
});
Other server controls or HTML junk
</div>
And then the code behind will find that div, and then move it into the ContentPlaceHolder.
protected void Page_Load(object sender, EventArgs e)
{
ContentPlaceHolder c = Page.Master.FindControl("ScriptsPlace") as ContentPlaceHolder;
HtmlGenericCOntrol jsDiv = this.FindControl("_jsDiv") as HtmlGenericControl;
if (c != null && jsDiv != null)
{
c.Controls.Add(jsDiv);
}
}
I actually put this code in a custom user control, and I just have my regular user controls inherit from the custom user control, so once I wrap the javascript/etc with a <div id="_jsDiv" runat="server">, the custom user control takes care of the rest and I don't have to do anything in the code behind of the user control.
What normally happens is
you set up your master pages with the proper html and ContentPlaceHolders
you create pages based off that master page. If you use Visual Studio, and tell it to create a new page based upon a existing Master page, it will add the Content areas for you.
you add things to the Content areas in the newly created page.
If you want to dynamically add controls to the master (or any) page, you could add controls to any existing control. If it shouldn't be wrapped in any way, just add a Placeholder (it is an asp.net control).
I did like this
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<asp:Literal ID="jsstuff" runat="server"></asp:Literal>
</asp:Content>
And this went into code behind:
string stuff = #"<script type=""text/javascript"">
var searchBox = 0;
var currentCountry = '';
</script>";
jsstuff.Text = stuff;
If the namespace for content Page and Master page is not same then the content page control not accessible in Codebehind in content page.
Also, check your designer files. if the control not listed in designer file then delete the file and recreate (project->convert to web application)
I have a anchor tag like this
<a href="" class="search gl">
<img src="_gfx/cmn/goButton.png" class="searchbutton" name="btn"></img>
</a>
Button from jquery I am setting this href based on different conditions to different page.
$(".search gl").attr("href", "test.aspx");
But when I click on that anchor its loading the test.aspx page but not hitting the page_load event.I have to add some more conditions in that page load. Please help me.
Thanks
if the page is loaded but the event is not hit probably you have missed to specify the handler for the page load.
if in your page you got AutoEventWireup="true"
remove the handler
swithc to design
double click anywhere on the page
it will add the handler in the Page.aspx.Designer
otherwise you have to do it manually
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Load += page_load;
}
You cannot have spaces in your class name:
Try:
<a href="" class="search_gl">
Then:
$(".search_gl").something(...);
Wrap that code inside $(document).ready() or $() and change the selector to .search.gl.
$(function(){
$(".search.gl").attr("href", "test.aspx");
});
If you want to use this link to post back to the same page then why do you are you setting href?