Validation using navigation - asp.net

I have some pages in my website and a left menu control. Control helps to navigate from one page to another.
My query is -> While user try to navigate to another page, I want to impose some validation like in the current page if the form is not saved, user will be asked to save it by using a confirm messagebox and if user presses no button, then user will be allowed to navigate otherwise, system will first save the details and then navigate.
Edit - My page is a content page, I meant, this is using a master page.

Use the following steps
window.onbeforeunload = confirmExit;
and a function that stops/continue the page execution.
function confirmExit() {
var email= document.getElementById("email");
if (email.value != "")
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}

The way I would do this is to have an onbeforeunload javascript event fire which gives the user the choice to save the form. I personally would also poll the form saving data back whist they are completing it. I think this is the method SO uses.
There is a pretty decent example over on Code Project that may help http://www.codeproject.com/KB/aspnet/AutoSaveFormData.aspx
EDIT:
If you only want to call the save method you can mark it with the [WebMethod] filter and call it using XmlHttpRequest or jQuery's $.post

Related

how to stop user to use back button

I have one button on page, page name abc.aspx . when user click on that button
it should redirect to finishwork.aspx page.
After finishwork.aspx page user must not go back to abc.aspx page. when user press back button in browser, he should be redirect to workallreadyfinish.aspx page
Disable caching on that pages and avoid caching the page.
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
location.replace() can be used to replace your page in the history.
There are many ways to accomplish this, but, as you are using ASP.NET and I'm going to assume, WebForms, why don't you make use of the <asp:Wizard> control?
You will be able to have a much detailed control over your steps and block the user to go back and all sort of nice things.
If you want to take the normal way, you can always warn the user that the page will no longer be valid using a javascript event.
You can also make use of hashing and submit the form by an ajax call instead of a normal POST
You can write a cookie once the form is submitted and the next time, show such warning, so even if the user goes back and press the Submit button again, you will not care. Remember to erase the Cookie on if (!Page.IsPostBack) { ... }
Having your user workflow around the browser back button is not such a good idea.
Browser back buttons are not entire in your control.
If you want to provide a logical back in your application, use a back button in your application.
If you only want that a user cannot go back to a page, you should tell the browser not to cache it set the page to expire.
You can use javascript function for this:-
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);

100% code-behind form post

I am looking for a way to wire up an ASP:LinkButton to appear as a link but in the background (100% in the code behind, no dummy pre-filled form in the markup) do a form post (target=_blank). I have a form action, method and parameters to pass that I will query for in the "click" event of the LinkButton. What is the best way to accomplish this?
Well there are LOTS of ways to do what i think you are trying to do :)
One problem; standard pop-up's don't fire event handler calls as they are mapped via post-back to the page i believe.
If you are happy with GET only submissions:
OPTION A:
Add your link button with no target set and setup a post back event handler for click
setup your URL and pass it back to the page into a JS function that will load right away eg or use jquery etc.
in the JS function you load the URL using window.open() with the target set to "_blank"
EFFECT:
User clicks the link, all code is server-side that works out the URL to show, page refreshes back to where it was and a popup window then loads showing the new URL
OPTION B:
Setup the link to have target="_blank"
make it call a new page or the same page with a querystring argument you can pre-process in the page_load()
in the new page or controlling block of code, do your calculations and Response.Redirect() to the new target
EFFECT:
User clicks the link, no page refresh just a new popup right away with a redirect to the new page. This is a cleaner solution i think!
IF you need POST support:
Dynamically create either elements or a string of HTML representing a form with all the needed input elements and output it into the popup window (using option b as a rough start template) and have a onload submit the form right away which will perform a POST to the URL you decided via server-side script giving the same effect as option b but with a form level POST.

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.

Implementing Back button functionality in asp.net

i need to implement a back button for my asp.net website.I am able to use the javascript method to acheive my requirement.But using this method sometimes I need to click on the back button multiple number times to go back to the previous page.It may be because we are using jquery tabs in our website.To focus on a particular tab,other than the 1st tab on page load I am using Page.ClientScript.RegisterStartupScript(....).So I am unable to take the user back to the previous page with just one click.
I also tried with asp.net-C# methods mentioned in the following link.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=89
I am able to go back to the previous page, but its state is being lost.Could someone please help me in acheiveing my requirement?
Details:
I have page1.aspx,page2.aspx(which contains jquery tabs view/edit).
In the page1.aspx there are 2 buttons(View,Edit).If I click on view button it takes me to page2.aspx View tab(1st tab) and if I click on the edit button it has to take me to page2.aspx with Edit tab loaded.both View/Edit tabs contain back button.
Also from the View tab I can navigate to the Edit tab,by clicking on another Edit button present in it.
Thanks.
The methods you have covered in your question are essentially what is available to you.
You can either
1. Provide a link that uses javascript to make the client go back a page.
2. Provide a link that posts back to the server that redirects you back a page.
I am not sure why the jquery in your webform as described in your question is causing you to click more that once to go back. If you know that it will always take 2 clicks to go back you could try this method:
javascript: window.history.go(-2)
When you are using the postback/redirect method you will always be using a http GET method to retrieve the page you are returning too. If you want to maintain state you will have to do this manually i.e. save the values when leaving the page somewhere, like session or a temporary database, and when returning to the page, during the page load, check to see if the user has these values saved and pre-populate them.
I've done something similar (with automatic redirections though) and I had to keep track of the number of pages to go back in my ViewState (or Session if you're jumping from page to page):
code-behind
public void Page_Load()
{
Session["pagesToGoBack"] = ((int)Session["pagesToGoBack"])++;
}
mark-up:
<input type="button" value="Back" onclick='javascript:history.go(<%= Session["pagesToGoBack"] %>);' />
Be careful to reset the session variable when needed
Made me feel a bit dirty but it worked :)

Close Browser Window after Form Post

Here's my situation.
I have a button on my ASP.NET webform. This button creates a new browser window pointing to a page which has a lot of hidden fields (which are dynamically generated). This form submits itself to SQL Reporting Services on the bodies onload event. This works fine and the report is displayed in this new window.
However, now I want to still POST a form to SQL Reporting services but I want to get back an excel spreadsheet. So I add another hidden input with a name of rs:Format and value of Excel. This works and the user gets the option to download the excel file.
However they are now stuck with the extra window that was created. How do I get around this? I've tried creating the dynamic form and POST in the same window, but then they see the (empty) page with the form, and not the page they generated the report from. I've tried closing the window that I've created but I don't know where to put the javascript to do this. If I put it on the onload, then the window closes without the form being submitted.
Any ideas for what to do here?
Edit: What I was doing here wasn't the best way of getting the result I needed. I ended up using a WebRequest to get the excel report from Reporting Services instead posting a form, therefore I didn't need the second window afterall.
Don't close the browser. It belongs to the user, even if you opened it. Closing it can make them mad.
Do redirect to a page the communicates to the user that you're done with the window. There you can provide a (javascript-based) link that make closing the browser a little easier if you want, though closing a browser window is generally pretty easy.
By the way, if the popup doesn't contain any useful output, what you may want to do is submit your form into a small Iframe within the page. This way there's no need to close a window, as the frame can be made invisible.
When user wants an Excel file, there's no need to pop up another window. I assume selection of Excel file or HTML report is done in some HTML control like a radio button or a checkbox. So, before doing anything, check the value of that radiobutton/checkbox with javascript and do the appropriate action. Something like:
function getReport(excelFormat)
{
if (excelFormat)
document.form1.target = '_blank';
else
document.form1.target = '_self';
document.form1.submit();
}
What if the button did an Ajax request back to the original page and got the hidden field values. You could then construct another form on the page with the hidden fields using javascript and submit it -- with the download option. Since the request will return an application/ms-excel file, it shouldn't refresh the current page but the download should still occur. You'd need to make sure that the button click didn't cause a postback by returning false from the client-side function. Note that this only works if the post of the generated form results in a download, not a new html page.
<script type="text/javascript">
function submitReport( button ) {
PageMethod.SubmitReport(onSuccess,onFailure,{ control: button });
}
function onSuccess(values,ctx) {
var form = document.createElement('form');
form.action = reporting-services.url;
form.method = 'post';
document.body.appendChild(form);
.... add hidden fields to form from returned values
form.submit();
document.body.removeChild(form);
}
function onFailure(error,ctx) {
... pop up some error message....
}
</script>
...
<asp:Button runat="server" id="reportButton" ClientClick="submitReport(this);return false;" Text="Report" />
Generally it's ok to close any popup window that your app has created.
This can be done with window.close() (which will pop up a confirmation if the window was not created by script).
If you want to be sure that the download is successful before closing the window, you will need to perform some server-side magic - have your server keep track of the download in progress, and poll it via AJAX from the popup window until the download completes.
Once the server tells you it's done, the window can be closed.

Resources