Trying to take user input and write to a file - c#

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(){}"

Related

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

show loading image using c# code behind

I am working on a web application where I want to show a loading image (busy indicator) when my code create a xml file and download it I want to show the image in a div. I should use c# code only not update panel nor the jquery ajax technique. My code looks like:
protected void lb_DownloadXML_Click(object sender, EventArgs e)
{
this.imgLoading.Visible = true;
//all my code
this.imgLoading.Visible = false;
}
my image is
<img src="Images/loading_big.gif" width="50" height="40" runat="server" id="imgLoading"
visible="false" />
but its not working. Can anybody explain me how can I achieve this task.
thanks in advance.
To execute server side code from client machine, there is no other way other than UpdatePanel or Ajax. The client request should reach to the server to execute the request. And the way this happens is by PostBack or by Get request. PostBack will reload page, if you are not using UpdatePanel (I guess which you don't want) and second is GET, which again you don't want.
Update
According to #Lloyd
Yes it is possible, you can render contents to the page sequentially by setting the "Response.BufferOutput" property to false, writing directly to the Response.Output and Flushing the stream.
You should well understand that when you write any code on server side it is only reflected in the broswer after a successful postback. Over here if you write C# code to display an progress image then it would be displayed only after the postback is successful, that means after your XML file has been created and downloaded to the client end or after successful execution of lb_DownloadXML_Click().
So there is no way to achieve that using C# server side code, you have to rely on client side programming to achievev this.

Problems when assigning values via JavaScript to Asp.net labels and then passing via C# session object

I am assigning variables to asp labels via javascript with a simple innerHTML call
example:
document.getElementById('labelName').innerHTML = parseFloat(var).toFixed(2);
It appears in the label fine, and I am able to continue to manipulate it via javascript.
I then set it up so that that variable is put into a session object via C# codebehind buttonClick event.
example:
protected void btnConfirm_Click ( object sender, EventArgs e )
{
Session["sessionName"] = labelName.Text;
}
The buttonConfirm_Click method fires it Response.Redirects to another page and populates asp labels with the session object via the c# codebehind page_load method.
example:
lblResult.Text = Session["sessionName"].ToString();
When doing this, the label is empty, no errors or 'null'. I have tried to narrow down the issue by trying various things. When I assign the text explicitly in the c# code behind of the first page and the recieve and assign it to the label on the next page, it shows correctly.
example:
Page 1:
Session["sessionName"].ToString() = "Test";
Page 2:
lblResult.Test = Session["sessionResult"].ToString();
I have tried several other things, such as casting the variables in javascript and in the codebehind, and checking to make sure I had runat="server" within each applicable label.
Anyways, is there something here I am missing? Is asp.net unable to detect the changes that javascript has made to the labels? Are there some incompatibility issues when using innerHTML or anything like this that maybe be causing such a thing to occur?
Thanks in advance!
The problem is that the text in a span tag (that is what asp:Label will render) isn't sent in the post to the server and therefore you can't read your changes server side. You'll need to use a input element (hidden field, textbox etc depending on what your ui should look like).

Make server-side validation without losing data on postback

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.

passing value from opener to popup and processing it server side, not client side. Cant use a GET

I have an aspx web page (opener) which opens a popup window
In the popup window I need to retrieve the value of a hidden field which exists in the opener page.
So this is all straight forward using Javascript.
However, here’s the problem, I need the value of the hidden field to be processed SERVER side before the pop up page loads
(Basically, the hidden field contains XML which need to be deserialized server side and the data used to construct the DOM of the popup page)
So how do I pass the data in the hidden field of the opener, to get processed serverside in popup?
The data is Waaay too long to be passed as a GET. i.e. in the querystring of the popup page
What are the other options here?
Retrieve it using Javascript in popup, then do a postback to reload the page (very ugly)
Somehow post the data when opening the popup? Is this possible and can I stil pass other info via the querystring
Any other ideas?
Have a form like this
<form method="POST" action="action.php" onsubmit="open_popup(this);">
<input name="really-big-field" type="hidden">
</form>
also, javascript like this
function open_popup(form)
{
window.open('action.php', 'actionpopup','width=400,height=300');
form.target = 'actionpopup';
}
window.open() will open a popup like you want.
Setting the form's target to the opened popup will make sure that the form will POST to that popup.
Since a POST is made, you can send larger data than you can send using GET.
You can process the data server side in action.php (or in ASP.Net/VB file).
My usual solution to this sort of issue is to use XmlHTTPRequest to post the XML to the server, which simply stores the XML against some unique ID such as a GUID and have the ID returned from the server.
The URL you provide for your popup would then only need to carry this ID rather than the whole XML. Now when the server code on the other end of that URL needs the XML it can use the ID to look up the XML (probably deleting it from its temporary store at the same time) and can process the XML as if had been posted in the request.
Edit: Sorry, I realize this doesn't answer your question. I didn't read it clearly enough and didn't realize you needed to do it server side. I suppose if you wanted to take this path, though, you could then AJAX up your page to build it.
Parent page:
foo = 'bar';
child = open ("popup.html");
// you can now access the new windows functions with child.varname and child.function()
Child page:
alert(window.opener.foo);
Should alert Foo. Therefore you can:
somevar = window.opener.document.getElementById('id').value;
to get the field's value.

Categories