I've got my code to post a javascript array in a form:
<form id="my_form" action="file:///C:/Users/John/Desktop/jquery/savetext.aspx" method="post" onsubmit="return prepare()">
<input type="text" id="file_name" name="file_name" rows="1" cols="20" />
<input type="hidden" name="seatsArray" />
<input type="submit" value="Save" />
</form>
<script type="text/javascript">
function prepare();
{
document.getElementById('seatsArray').value = seatsArray.join();
return true;
}
</script>
Can anyone help me out with the savetext.aspx action file that I need, as my knowledge of ASP.NET is minimal (I'm used to PHP, but this one needs to be ASP.NET).
I guess I can have a crack at getting somewhere near:
<%# Page Language="C#" %>
<script runat="server">
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = "file:///C:/Users/John/Desktop/jquery/txtfiles/" + request.form("file_name");
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(request.form("seatsArray"));
sw.WriteLine("");
}
}
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
</script>
Am I on the right track?
Many Thanks!
I think you should just use the form as intended, and just add the array data to a hidden element..
<form id="my_form" action="http://my_site/savetext.aspx" method="post" onsubmit="return prepare()">
<input type="text" id="file_name" name="file_name" rows="1" cols="20" />
<input type="hidden" name="seatsArray" />
<input type="submit" value="Save" />
</form>
<script type="text/javascript">
function prepare();
{
document.getElementById('seatsArray').value = seatsArray.join();
return true;
}
</script>
and on the server side use request.form("file_name") and request.form("seatsArray")
you need use the Stream Class. This is a short code for write / create text files in ASP.NET using VB.NET.
Dim strStreamW As Stream
Dim strStreamWriter As StreamWriter
Try
Dim ds As New DataSet
Dim FilePath As String = "C:\nombreArchivo.txt"
'Open the file, if not exists create it
strStreamW = File.OpenWrite(FilePath)
strStreamWriter = New StreamWriter(strStreamW, _
System.Text.Encoding.UTF8)
'Using a conection with the db
ds = Negocios.TraerDatosArchivo()
Dim dr As DataRow
Dim Nombre as String = ""
Dim Apellido as String = ""
Dim Email as String = ""
For Each dr In ds.Tables(0).Rows
'Get the recordset
Nombre = CStr(dr("Nombre"))
Apellido = CStr(dr("Apellido"))
Email = CStr(dr("Email"))
'Write the line in the file or "stream"
strStreamWriter.WriteLine(Nombre & " " & Apellido & " - " & Email)
Next
strStreamWriter.Close()
Catch ex As Exception
strStreamWriter.Close()
MsgBox(ex.Message)
End Try
Related
My notify url is not working even it is already activated in paypal. Is there something wrong with my code in the form? i have the same notify url in paypal account. By the way, I'm using heroku,spring mvc. Thanks. I hope you can help me.
<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_donations"/>
<input type="hidden" name="business" value="1234businessaccount#gmail.com"/>
<input type="hidden" name="item_name" value="${student.lastname }, ${student.firstname}"/>
<input type="hidden" name="currency_code" value="PHP"/>
<input type="hidden" name="lc" value="PH"/>
<input type="hidden" name="rm" value="2"/>
<input type="hidden" name="return" value="http://atriev.herokuapp.com/"/>
<input type="hidden" name="cancel_return" value="http://atriev.herokuapp.com/atriev-index.html"/>
<input type="hidden" name="notify_url" value="http://atriev.herokuapp.com/paypal.html"/>
paypal.jsp
<%# page import="java.util.*" %>
<%# page import="java.net.*" %>
<%# page import="java.io.*" %>
<%
// read post from PayPal system and add 'cmd'
Enumeration en = request.getParameterNames();
String str = "cmd=_notify-validate";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
// post back to PayPal system to validate
// NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
// using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
// and configured for older versions.
URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
// assign posted variables to local variables
String itemName = request.getParameter("item_name");
String itemNumber = request.getParameter("item_number");
String paymentStatus = request.getParameter("payment_status");
String paymentAmount = request.getParameter("mc_gross");
String paymentCurrency = request.getParameter("mc_currency");
String txnId = request.getParameter("txn_id");
String receiverEmail = request.getParameter("receiver_email");
String payerEmail = request.getParameter("payer_email");
if(res.equals("VERIFIED")) {
// check that paymentStatus=Completed
// check that txnId has not been previously processed
// check that receiverEmail is your Primary PayPal email
// check that paymentAmount/paymentCurrency are correct
// process payment
}
else if(res.equals("INVALID")) {
// log for investigation
}
else {
// error
}
%>
I want to get uploaded file from one page to another page and then save to my online server.
My Code is
First Page:
<html>
<body>
<form action="http://localhost:3132/Sample/api/Test.aspx?frm=31" method="post" target="_blank">
Name: <input type="text" name="f1" id="f1"><br>
Email: <input type="text" name="email" id="email"><br>
FileName: <input type="file" name="file" id="file"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Second Page:Entries.aspx
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
System.Data.DataTable dtData=new System.Data.DataTable();
foreach (string strKey in Request.Form.AllKeys)
{
if(strKey.Equals("data.xml") || dtData.Columns.Contains(strKey))
continue;
dtData.Columns.Add(strKey);
System.Data.DataRow dr=dtData.NewRow();
if(dtData.Rows.Count>0)
dr=dtData.Rows[0];
dr[strKey]=Request.Form[strKey];
if(dtData.Rows.Count<1)
dtData.Rows.Add(dr);
}
string strFileName = string.Empty;
string newFilename = string.Empty;
string fileName = System.IO.Path.Combine(Server.MapPath("~/APIUploaded"), Request.Params["filename"].ToString());
newFilename = Guid.NewGuid().ToString();
System.IO.FileInfo fInfo = new System.IO.FileInfo(fileName);
newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension);
strFileName = System.IO.Path.Combine(Server.MapPath("~/APIUploaded"), newFilename);
using (System.IO.FileStream fileStream = System.IO.File.Create(strFileName))
{
/*Getting stream from the Request object.*/
using (System.IO.Stream stream = Request.InputStream)
{
int byteStreamLength = (int)stream.Length;
byte[] byteStream = new byte[byteStreamLength];
/*Reading the stream to a byte array.*/
stream.Read(byteStream, 0, byteStreamLength);
/*Writing the byte array to the harddisk.*/
fileStream.Write(byteStream, 0, byteStreamLength);
}
}
Through the second page I am getting form values with uploaded file name. When I am going to save to my Online server folder, the file contents are empty. Is this possible to get uploaded file from one page to another page by using file upload control in asp.net?
You need to add the enctype to the form:
<form action="http://localhost:3132/GoLeadsUpdate/api/Entries.aspx?frm=31"
method="post" target="_blank" enctype="multipart/form-data">
.
.
.
</form>
And I think you have to look at Request.Files: http://msdn.microsoft.com/en-us/library/system.web.httprequest.files(v=vs.110).aspx
Hello I'm new to cshtml and I have web pages in ASP.NET Razor v2 I would like to insert some data into DB on button click. These data are provided from various textboxes and also uploading picture. May I please know how to how to provide action on button click?
I tried this in my cshtml file :
<button type="submit" name="action" value="insertRegistered">Uložit</button>
#if (action == "insertRegistered")
{
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=6";
db1.Execute(sql, fileName, fileContent, fileMime);
}
In WebMatrix, you can accomplish this in this way:
Razor code:
#{
var fileName = "";
var fileContent = "";
var fileMime = "";
var IDservice = "";
#*TEST CODE *#
#*if (!IsPost)
{
IDservice = "1";
var db = Database.Open("StarterSite");
var dbCommand = "SELECT * FROM services WHERE IDservice = #0";
var row = db.QuerySingle(dbCommand, IDservice);
fileContent = row.fileContent;
fileMime = row.MimeType;
fileName = row.fileName;
} *#
if (IsPost)
{
fileName = Request.Form["fileName"];
fileContent = Request.Form["fileContent"];
fileMime = Request.Form["fileMime"];
IDservice = Request.Form["IDservice"];
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=#3";
db1.Execute(sql, fileName, fileContent, fileMime, IDservice);
}
}
And the markup should look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Service</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>Service Information</legend>
<p><label for="fileName">FileName:</label>
<input type="text" name="fileName" value="#fileName" /></p>
<p><label for="fileContent">File Content:</label>
<input type="text" name="fileContent" value="#fileContent" /></p>
<p><label for="fileMime">Mime:</label>
<input type="text" name="fileMime" value="#fileMime" /></p>
<input type="hidden" name="IDservice" value="#IDservice" />
<p> <button type="submit" name="action" value="insert Registered">Uložit</button></p>
</fieldset>
</form>
</body>
</html>
And here's a working sample.
Here's a set of tutorials which, I believe, should be very helpful!
Put your database logic into a controller action, like this:
public class HomeController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// Do database update logic here
// Upon successfully updating the database redirect to a view
// that displays the information, read-only version not editable
return RedirectToAction("Index");
}
catch(Exception ex)
{
// If something went wrong, then re-display the view
// the user tried to update database from
return View();
}
}
}
Now in your view create a form by using the HTML helper Html.BeginForm(), like this:
#using (Html.BeginForm("ActionMethodName","ControllerName"))
{
... your input, labels, textboxes and other html controls go here
<input class="button" id="submit" type="submit" value="Uložit" />
}
Note: Html.BeginForm() will take everything inside of it and submit that as the form data to the controller action specified as parameters to it.
In my web site I have "contuct us" page and I want the manager able to reply via email
to the customers.
All the process need to be in the server side.
It is important to note that I works with Webmatrix development environment...
So considering my web development what is the simple way for me to add the ability to
send email?
My HTML code is:
foreach(var row in db.Query(displayApplicant,nameOfcustomer))
{
<tr>
<td class="dispExpertActScreen">#row.messegeID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.email</td>
<td class="dispExpertActScreen">#row.isCustomer</td>
<td class="dispExpertActScreen">#row.userID</td>
<td class="dispExpertActScreen">#row.content</td>
<td class="dispExpertActScreen">answer the question</td>
<td class="dispExpertActScreen">remove</td>
</tr>
}
the javascript function: (to save details in hidden fields)
<script type="text/javascript">
function answerBox(messegeID,userID) {
var msg = prompt('answer to customer:');
document.getElementById('answer').value = msg;
document.getElementById('ansMode').value = 'true';
document.getElementById('msgID').value = messegeID;
document.getElementById('user').value = userID;
document.getElementById('ansMessege').submit();
}
</script>
the hidden fields:
<form method="post" id="ansMessege" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="answer" id="answer" value="">
<input type="hidden" name="msgID" id="msgID" value="">
<input type="hidden" name="user" id="user" value="">
<input type="hidden" name="ansMode" id="ansMode" value="">
</form>
the asp.net code:
<%# Import Namespace="System.Web.Mail" %>
#{
Layout = "~/_ManagerLayout.cshtml";
Page.Title = "Management Applications";
}
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayApplicant="";
var nameOfcustomer="";
var category="";
var yesNo="";
if(IsPost)
{
if(Request.Form["ansMode"] == "true")
{
var selectQuery="SELECT * FROM messegesFromCustomers";
var id=Request.Form["msgID"];
var msg=Request.Form["answer"];
var user=Request.Form["user"];
foreach(var row in db.Query(selectQuery))
{
if(row.messegeID == Convert.ToInt32(id))
{
if(row.isCustomer == "yes")// **send the messege to customer account**
{
var insertQuery="UPDATE messegesFromCustomers SET answer=#0 WHERE messegeID=#1";
db.Execute(insertQuery,msg,id);
Response.Write("<script>alert('your answer sent successfully');</script>");
break;
}
else
{
// **Send messege to Occasional customer via email**
// **here I want to add code for sending email...**
string from = "ofirhgy#gmail.com";
string to = "ofirhgy#gmail.com";
string subject = "Hi!";
string body = "How are you?";
SmtpMail.SmtpServer = "mail.gmail.com";
SmtpMail.Send(from, to, subject, body);
break;
}
}
}
}
}
}
As you see I try to use WebMail.Send(...) but I don't know how...
In addition to that I saw that someone wrote that there is need to add some code
to the Web.config or something like that....
thanks you for help.
Edit:I edit the code and I put the line:
<%# Import Namespace="System.Web.Mail" %>
in the top of the asp.net page but I get this error:
Parser Error Message: A space or line break was encountered after the "#" character. Only valid identifiers, keywords, comments, "(" and "{" are valid at the start of a code block and they must occur immediately following "#" with no space in between.
Can anybody place for me the exact code?
First, we need to import the System.Web.Mail namespace:
<%# Import Namespace="System.Web.Mail" %>
Sending the message is a matter of calling SmtpMail.Send() with the following arguments: sender, recipient, subject and body. For example, we'd send an email in C# like this:
string from = "sender#example.com";
string to = "recipient#example.com";
string subject = "Hi!";
string body = "How are you?";
SmtpMail.SmtpServer = "mail.example.com";
SmtpMail.Send(from, to, subject, body);
SmtpMail.SmtpServer lets you specify the mail server used to deliver your message.
Content from here
I found a solution to that
In my code I added this and the email sent sucessfully:
if(isCustomer == "yes")
{
db.Execute(insertQuery,msg,id);
db.Execute(deleteQuery,id);
}
else
{
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.EnableSsl = true;
WebMail.SmtpPort = 587;//25
WebMail.UserName = "my gmail user name";
WebMail.Password = "my gmail password";
WebMail.From = "my address of email";
// Send email
WebMail.Send(
to: email,
subject: "Message from "some name of site" - Site",
body: msg);
db.Execute(deleteQuery,id);
}
I am in asituation ,where i have to redirect from asp to aspx page with parameter.I tried a lot of option,but the redirection is working ,but i couldnt the value in my aspx.cs page.
Below is my asp
Dim objASPError,strRemoteIP
Set objASPError = Server.GetLastError
The below is not working with parameter
'Response.Status = "301 Moved Permanently"
'Response.AddHeader "Location", "/404.aspx? err="+objASPError
'Response.End
I even tried by setting the hiddenn value and accessed the form element in aspx.cs
document.getElementById("hdnErr").value=objASPError
The below is also not working with objASPError
response.Redirect("/404.aspx?err="&objASPError)
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="404.aspx">
<input type="hidden" id="hdnErr" />
</form>
</body>
</html>
My aspx.cs
Label lbl = new Label();
Exception ex = Server.GetLastError();
string message=string.Empty;
if(Request.Form["hdnErr"] != null)
{
message = Request.Form["hdnErr"].ToString();
}
if (Request.QueryString["err"] != null)
{
String temp = Request.QueryString["err"].ToString();
lbl.Text = temp;
}
Thanks
Question
I understand sending the values through querystring is not a best option ... How to send error object from asp to aspx..
try changing
<input type="hidden" id="hdnErr" />
to
<input type="hidden" name="hdnErr" />
Also, Server.GetLastError returns an object so you can't combine it with a string. Take a look at the example in the msdn doc.
ASPError Object