I have a calendar named poDateCalendar, I wanted to make it so whenever the user selects the calendar to be any earlier than today's date, there will be a response as follows:
protected void poDateCalendar_SelectionChanged(object sender, EventArgs e)
{
if (poDateCalendar.SelectedDate < System.DateTime.Today)
{
Response.Write("<script>alert('Warning: you are selecting a PO date earlier than today's date')</script>");
}
poDateCalendar.Visible = false;
poDateBtn.Text = poDateCalendar.SelectedDate.ToShortDateString();
}
It worked the first time I tried it, but somehow now it doesn't work anymore, is there anything I did wrong?
I also tried doing breakpoints, it passed through the if statement and did run the response.write. However, there's just nothing that is displayed after.
Just replace your code with the following line
Response.Write("<script> alert(\"Warning: you are selecting a PO date earlier than today's date\");</script>");
In your case your code is failing because you have a single quote at "today's" which is making your code to fail. So I am using escape sequence at start and end of alert message.
Check the raw HTML sent to the browser. Likely that script was rendered before the opening html tag. There is no page or DOM yet, and so even if the browser ran the javascript at all it wouldn't know what to do with it.
This happens because of where you are in the ASP.Net Page Life Cycle at the time that code runs. A page class in ASP.Net works by first building up all of the controls and properties to have the correct data. Then, once that is all finished, there is a rendering phase where those controls are transformed into HTML for your browser. Before this rendering phase, anything you send to Response.Write() is going to a response stream that hasn't even sent headers to the browser yet.
To get around this, instead of writing to the Response stream direclty, use the Page.RegisterStartupScript() method.
I don't quite get the point - Allow users to do what they're not supposed to do, and then shout when they do so. + Message box / alerts are the old school ways of doing things. That's a bad user experience, IMHO.
I have a better suggestion here for you. You could instead disable to previous dates so that they can't select in first place. You can use DayRender event for that.
<asp:Calendar ID="poDateCalendar" runat="server" OnDayRender="poDateCalendar_DayRender" />
In code-behind:
protected void poDateCalendar_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Today)
{
e.Day.IsSelectable = false;
// Additionally grey out dates if you want
}
}
Related
I have written some codes in !IsPostBack block. This code is getting executed when the page loads for the first time. That is fine. But the problem is, when I refresh the page by hitting the f5 key this executes again which I don't want to do. I have searched many articles and found difference between PostBack and refresh. I know about this. But my question is difference between !IsPostBack and Refresh. Can we write some code which executes only when the page loads for the 1st time not when we refresh the page. By the way I have written my !IsPostBack block inside Page_Init() method and I am using c# for codebehind. Thanks.
Refersh and IsPostback are somewhat unrelated:
Refresh in browser generally mean "re-run last action that resulted in this page". Usually it causes GET request, but it as well can cause POST if page was shown as result of postback. Side note: you often can find sites warning you not to refresh page during non-reversible operations like "charge my credit card" as it may trigger duplicate post.
IsPostBack simply states that request come to server as POST, not GET.
Combining that you can get Refresh that triggers either branch of if (IsPostBack) check. In most cases so server will receive GET request and hence execute !IsPostBack branch.
If you really need to detect if page was rendered once already - setting cookie or writing information into Session would be reasonable solution.
Please change your code behind code as given below.
Boolean IsPageRefresh;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
}
I have got an ASP-Site, which enables the user to Add Label-Elements. I don’t know how many Labels where added or which ID they have. I know only, they will be within the Panel pnl_Added. After the user has added all his labels, he pushes a Send-Button for Update.
So, now I am at my Server, awaiting this postback, but I don’t know where, when and how to find out, which Elements were Added to pnl_Added. Can somebody help me?
I have tried something like that:
protected void Page_Load(object sender, EventArgs e)
{
[...]
for (int i = 0; i < pnl_Added.Controls.Count; i++)
{
[...]
}
[...]
}
But I think it is too late because of the loaded ViewState? Is that possible?
I am working with VS 2013, ASP c#, with the .Net Framework 4.
On server, controls tree doesn't created from actual client HTML. Actually, server doesn't know anything about client HTML besides input tags values in scope of submitted form. In general, all controls available in Page_Load method, created on server side from aspx file markup.
To implement your scenario, you need to add hidden field for each label, added from client and save label's inner text into hidden field's value. Then you'll can get these labels texts as below:
var labels = Request.Form["hiddenField's name"] as string[];
You should go one lever deeper and take the added elements from Request variable, because the control pnl_Added doesn't know about them as there was no postback.
Something like this:
Request.Form["field_id"]
I suggest to run the page in debug mode, review Request.Form collection and find what you need. You should see your label elements there.
I have visited the Telerik's website and viewed their demos etc...
But I am having problems trying to load content (html) in the RadEditor.
I have a Button_Click event where I get my html string and then set it to the RadEditor. The RadEditor is inside a RadWindow and only becomes visible when the button is clicked.
protected void btnSubmitHtml_Click(object sender, EventArgs e)
{
RadEditor1.Content = "<p>hello there</p>";
RadWindow1.Visible = true;
}
This doesn't show the html inside the RadEditor for some odd reason. I suspect it is the page life cycle that is involved with this problem.
Are there any suggestions to solve this?
I have encountered this problem multiple times and never found a "Proper" resolution.
However, a great work around is to simply set the content from the clientside via injected script. The end result is the same, and if you can tolerate the 10 millisecond delay, worthy of consideration.
EDIT after comment requested reference
Basically all you need to get an instance of the editor using ASP.NET WebForms $find function. That takes the html ID of the root of the rendered object and returns the client side viewModel if one exists.
The $(setEditorInitialContent) call at the end assumes that jQuery is present and delays the execution of the function till page load.
<telerik:radeditor runat="server" ID="RadEditor1">
<Content>
Here is sample content!
</Content>
</telerik:radeditor>
<script type="text/javascript">
function setEditorInitialContent() {
var editor = $find("<%=RadEditor1.ClientID%>"); //get a reference to RadEditor client object
editor.set_html("HEY THIS IS SOME CONTENT INTO YOUR EDITOR!!!!");
}
$(setEditorInitialContent);
</script>
Take a look here to see how to get a RadEditor to work in a RadWindow: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-radeditor-in-radwindow.html.
Said shortly, here is what you need to have in the OnClientShow event of the RadWindow:
function OnClientShow()
{
$find("<%=RadEditor1.ClientID %>").onParentNodeChanged();
}
To edit Html code only you can add -
EnableTextareaMode="true"
Add this property to the RadEditor.
I suspect that the way the control tries to interpret the html might be one of the problems. The other thing that may be causing this problem is the page life cycle.
This is not browser specific - the behavior exists in Firefox and IE. The RadControl is being used within a User Control in a SiteFinity site.
Very little customization has been done to the control.
<telerik:RadDateTimePicker ID="RadDateTimePicker1" runat="server"
MinDate="2010/1/1" Width="250px">
<ClientEvents></ClientEvents>
<TimeView starttime="08:00:00" endtime="20:00:00"
interval="02:00:00"></TimeView>
<DateInput runat="server" ID="DateInput"></DateInput>
</telerik:RadDateTimePicker>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadDateTimePicker1.MinDate = DateTime.Now;
}
}
[Disclaimer, I work for Telerik]
I don't specifically know what the issue is, however here are some general troubleshooting steps that might help unearth the issue:
Check for Javacript errors - (Firefox's Error Console would do it)
Isolate the RadDateTimePicker control from Sitefinity - (Create a normal ASPX page and place the RadDateTimePicker control on this page. Does it work in this environment?)
Check for stylesheet issues using Firebug and/or remove stylesheets (backup first).
In general, keep simplifying until it starts working then re-add complexity until it breaks again. This normally tells me where the problem is.
Alternately, you could send your project/code to Telerik support. Best of luck.
Can you try changing MinDate to use:
RadDateTimePicker1.MinDate = System.DateTime.Parse(String.Format("{0}/{1}/{2}", System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Year - 1))
And tell me if the behavior changes.
Also, is the new highlight being shown as well, or is it stuck on the old highlighting completely?
I don't know alot about ASP.Net but I'm trying to make a new control for a message box. You enter some info and press a button.
However, for some bizarre reason when the button is pressed, Page_Load() gets called a second time, and all of the member variables are reset to null! I need those variables, and Page_Load() has not reason to be called a second time! Of course the callstack is useless.
Remember, in ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.
Always two there are, no more, no less. A request and a response.
When the page posts back, the Page_Load method is called. Then, once the server actually processes the page and sends you a new one based on changes, the Page_Load is called again, actually the first time on the new page sent to you.
So if you are pulling data in the Page_Load event or setting some values, enclose it in the following block:
if(!Page.IsPostBack)
{
}
to preserve some of your state. Otherwise, the instructions that you put into the Page_Load event will execute every time.
It helps to review the ASP.Net page lifecycle :)
As Joel mentioned, instance variables will be lost once the page is sent back to the client. However, there are various methods of storing the values of your variables so you can retrieve them later. This page on State Management is a good starting point if you want to learn more.
Any tag/element which requires url reference like img, anchor, object etc must be checked for the empty reference.
e.g. href="", url="", src="" are some common errors.
This code works for me:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["something"] == null)
{
Session["something"] = "1";
}
else
{
Session["something"] = null;
//your page load code here
}
}
}
For me, the issue was a bit complicated, but I found that the
protected override void OnPreRender(EventArgs e)
handler is only called once, so it's safer to put some actions in there if it's not too late in the pipeline for you.
An extension of #user3207728's response, I found this link explains it well and has a simple solution...
http://www.aspdotnet-suresh.com/2010/04/detect-browser-refresh-to-avoid-events.html
Unfortunately checking just for if (!Page.IsPostBack) is not enough as IsPostBack will always be FALSE on a refresh.
Just a shot in the dark but maybe add this after your page_load:
if (!IsPostBack)
{
you can use sessions or viewstate to retain the values of variables..
if you want to redirect to a different page , use session[]
else if you want to stay on the same page , use viewstate[]
In my Case the Problem Was Related to Iframe, One Time I removed the Iframe Everithing Work Fine
<iframe id="pdf2"
src="#"
width="100%"
height="100%">
</iframe>