Make server-side validation without losing data on postback - c#

I would like to know which is the best way to do this: I have a form using ASP that is being validated firstly on client-side with jQuery. In this form I have a FileUpload control to upload an Excel file and the validation of this control is being made on server-side to check the file type, valid data, valid structure, etc... I really need to make the file validation on server-side to be as secure as possible and I don't want to use ActiveX.
The problem is that, when the server-side validation returns an error, the previously inserted data in the form is lost due to the postback.
Is there a way to make client-side validation, then after this is done, make the server-side validation and on the postback don't lose the sent data?

I think the best way to do that is to get old values of field at Page_Load.
All you have to is check if page is postback.
if (Page.IsPostBack)
{
YourTextBox.Attributes.Add("Value", YourTextBox.Text);
}
Hope this help you.

Try adding a CustomValidator to you form that will call the FileUpload.SaveAs() method and that will validate the uploaded file.
For example:
protected void ValidateCstm_ServerValidate(object source, ServerValidateEventArgs args)
{
//Upload the file
fileUpload1.SaveAs(....
.....
.....
//Validate the fileUpload
.....
//If the fileUpload is invalid
args.IsValid = false;
}
I hope that this helps.

Have you considered using AJAX for the file validation, thus avoiding a full post back altogether? There are several AJAX-based file upload widgets 'out there' that might serve your purposes...

just when you encountered any error on server side , set all your form post data in some session variable and redirect to the form and show the form filled up with this session data.

Alternatively you can use jQuery File Upload component. It does not require post backs. It needs server to handle HTTP GET, POST and DELETE and return JSON. You can use ASHX for this. This way your server side validation will not interfere with post backs.

Related

Trying to take user input and write to a file

i'm having a problem where I am trying to save the geolocation of an address unto a file. I am using hidden labels to transfer the information.
on the client side button event I have:
function save() {
document.getElementById("hidLat").value = y;
document.getElementById("hidLon").value = x;
<% saveAddress s = save(); %>
}
and in c# I have:
protected saveAddress save()
{
saveAddress s = new saveAddress();
s.latitude = hidLat.Value;
s.longitude = hidLon.Value;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\savedAddresses.txt", true))
{
file.WriteLine(s.latitude + " " + s.longitude);
file.Close();
}
return s;
}
When I click on the button the file is created but nothing is saved into it.
Am I doing this right or is there a better way to try and write the user input into a file?
I think you're getting confused on the web lifecycle. In your particular instance, this is what is happening:
Your page is requested, and the ASP.NET Runtime loads your code behind and attempts to execute the page.
In the process of executing your page, the ASPX contains code to call
saveAddress s = save()
In this way, that method is called before the page is even rendered back to the client.
When the page is finally sent down to the client, you have some client side code invoking function save().
Im guessing you want that server side method to be invoked after the javascript function has run. You have two options:
Full PostBack - You post the form back to the server, and your ASPX code behind can have some code there to inspect Page.IsPostBack and attempt to call your server side method.
Ajax - You can make an ajax request to a specific handler on your site and then invoke your server side save method.
Are you sure the latitude and longitude variables are set? Try printing them out first..
Code seems OK
It appears you are confused about about transferring values between server and client code. Seeing the markup would be useful. I am assuming you are using webforms <asp:Label /> control. In order to transfer values to the server you need to post a form or make an XMLHttpRequest. There are other ways but we will just stick with these two for now.
Also remember that if these labels are server controls their values are stored in viewstate. Modifying the value with javascript will not affect the view state. I would recommend storing the values in a hidden form input field. Add your save logic to a save OnClick server side.
Comment
You don't want to use
file.Close();
when you use "using(){}"

Dynamic data for JQuery in ASP.NET pages

Problem
I have some pages that need dynamic data from website to generate output to users.
A simple solution is an aspx(php, ...) page to generate data and create another html page serving as GUI retrieving data from first page and showing it to users. in this method I can call my GUI page for example form1.aspx and my data page form1.json.aspx.
although I personally like this method, it is not suitable when creating components for it.
Another method that currently I'm using is using same GUI page call itself with a querystring to retrieve data. this page should check for that query string and if it exists, only generate data and remove everything else from page. As an example for this method if I call my page form1.aspx, to retrieve data, I need to call it like form1.aspx?JSON
Here is an example of what I'm doing:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString.ToString().IndexOf("JSON") == 0){
this.Controls.Clear();
Response.Clear();
// send pure data to client
} else {
// render page as GUI
}
}
However this method becomes too messy if I add master page and/or inherit my page from some template page. Master pages can only removed in Page_PreInit and that adds another extra method.
Security controls cause another problem, if user leaves page open for long time until session expires any attempt to retrieve data will fail cause security module will redirect the request to login page.
Next problem is I cannot consolidate my component in package because it needs modification in page (removing master page, clearing page components ...).
What I'm looking for:
1- I'm looking for a solution that I can call my page and get pure data (JSON or XML format) and doing so run a server side method that generates data, so I don't have to worry about what another designer puts in their master page or template.
2- I think it is possible to use axd extension to do this but I don't have a clue about it and couldn't find a helping document either.
3- Is there any better way of doing this. any suggestion or solution to improve this much appreciated.
Page methods. Check this article: http://weblogs.asp.net/craigshoemaker/archive/2008/09/29/using-jquery-to-call-asp-net-ajax-page-methods.aspx or http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
WCF JSON service: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
Other ways of doing is using an HTTP Handler. Implement IHttpHandler interface and register your implementation in your Web.config file. Later call it using jQuery ($.get / $.post):
http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx
EDIT
As OP pointed out, in order to access session state in a page method you should use WebMethodAttribute this way:
[WebMethod(EnableSession = true)]
I think you can use webservice instead of aspx page to return a JSON or XML string and then the caller page (any aspx page) will response after process is success.
So with this webservice, any third party page will have access to your server side method.
To create a webservice pls Check this link: Create and use Asp.net web service basic
Regards

Pass data to server side from Javascript code

I'm trying to send data from client-side to server-side (asp.net c#), if you really want to know, I want to send the window.name property.
First I thought about having a asp:HiddenField and on the OnSubmit event have some JS write the value in the hidden field. The only problem is that I can access the hidden field value (according to this) only from PreLoad event to PreRenderComplete event. The project that I'm working on has a lot of code in the OnInit event, and unfortunately I cannot move it and I need to use the window.name value here.
The other ideas that I have is to add a custom HTTP Header windowId or on the OnSubmit event have a JS that appends a parameter to the document.location.href.
I managed to write to the header from JS with the XMLHttpRequest setRequestHeader, but, maybe I did something wrong in my implementation, this generates 2 requests, the first one is the normal, expected one(clicking a button/link ...) and the second is from the XMLHttpRequest. I find this behavior very unnatural. Do you have any sugestions? (see code snippet below). I do not what to use AJAX.
var oReq = new window.XMLHttpRequest;
oReq.open('POST', document.location, false);
oReq.setRequestHeader("windowId", window.name);
oReq.send(null);
For the OnSubmit hook idea, i haven't spent to much time on it, but i think I have to append the # character before i append my windowId parameter with it's value, so that the page doesn't reload. I might be wrong about this. Any way, I have to remove this from the URL after I take the value, so that the user doesn't see the nasty URL. Do you have any sugestions?
Ok so what are your ideas?
Thank you for reading all my blabbering, and thank you, in advance, for you answers.
I would recommend the <asp:HiddenField /> (e.g., <asp:HiddenField ID="hfWindowName" runat="server" />. In OnInit you can still access its value by using Request.Form:
string windowName = Request.Form(hfWindowName.UniqueID);

asp.net: how do i prevent users from posting the same data multiple times

i have a little asp.net web application.
it is a front end to a sql-server-2008 database.
after they fill out all the data, they will press submit and the data will be sent to the database.
after this point if the user refreshes the page, the data is posted again!!! how do i disable this from happening?
Send a Location header back to the user that redirects the browser to another page: refresh will then reload that other page rather than resubmit the old form.
This is caused by the last request being a POST request to the page, what do you need to do is a redirect so the last request becomes a GET.
After you have handled the post data you can just do a redirect to the same page with:
Response.Redirect("~/ThePage.aspx");
This will prevent you from presenting a message to the user straight from the code behind, if you want to present a success message using this method you will need to add a querystring or something similar:
Response.Redirect("~/ThePage.aspx?result=success");
And then check on the page bind if the querystring to present a success message is set, such a check could look something like this:
if (Request.QueryString["result"] != null && Request.QueryString["result"].ToString().ToLower() == "success")
{
//Show success message
}
Another solution which probably is superior but might require some more work is to wrap the form in a updatepanel, you can read more about it here: http://ajax.net-tutorials.com/controls/updatepanel-control/
An updatepanel will make the form submit with AJAX instead of full postback.
You need to follow the Post/Redirect/Get pattern which is explained on WikiPedia and alluded to by Femi. In your code after you've done your processing do a Response.Redirect to the desired page.
See this article about the PRG pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get
In short, after the user POSTs (submits) data to your server, you issue a Response.Redirect to have the users browser GET a page. This way, if the user presses the reload button, it is the GET request that is repeated.

How to post params from javascript to asp.net?

I have a javascript code which builds a link with 2 params.
Now, I know how to post these params using the address, but I don't want to use it.
I've tried using cookies for posting the params, but somehow I can't read them on the server side.
this is the client side code
document.cookie="name="+"value";
this is the server side reading code
string s = Response.Cookies[cookieName].Value;
Can you hep me out?
Create a mini form (not an asp.NET web form, just a simple one) with two input type hidden fields named as your parameters. After that create a link or button an tie the onclick event of it to a javascript function (example: onclick="javascript:postIt();").
Then when user clicks the button or the link the function will replace the value of those parameter something like:
document.miniform.parameter1.value = yourvalue1;
document.miniform.parameter1.value = yourvalue2;
document.miniform.submit();
To get the parameters back into code use Request.form("parameter1") and so on...
You can use an Ajax Request to post your data to an ASP.NET form.
To post data to any page, you HAVE TO use the path to that page. As for your problem with setting the cookies, they can only be used by a page in the same domain.
Are you doing an HTTP Post? You could post these values inside a form field. I'd use a hidden input field. You can add one in your markup or add one via the javascript.
Your other option is to use some sort of Ajax and pass JSON or XML in the body of the post.
Cookies are meant to save data client side accross pages and/or sessions.

Categories