UPDATE
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (default.aspx):
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
When my default.aspx page gets loaded up, it calls the following function:
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my web.config file to make this work properly? Request.Params("<param name>") does not work.
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
In the code behind of Default.aspx:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.
As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.
Why not use System.Net.WebClient?
Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)
System.Net.WebClient wc = new System.Net.WebClient();
byte[] b;
byte[] res;
string formdata = "text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit";
// encode the form data string into a byte array
b = System.Text.Encoding.ASCII.GetBytes(formdata);
// set the content type for a form
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// POST and get data
res = wc.UploadData("http://localhost:51816/gs_ontheweb/default.aspx", b);
//convert the return page from byte[] to ascii
string s = System.Text.Encoding.ASCII.GetString(res);
Related
I want to POST to URL but following making it as GET , so How can I POST the
Object portletResponse = webAppAccess.getHttpServletRequest()
.getAttribute(Constants.PORTLET_RESPONSE);
if (portletResponse instanceof javax.portlet.ActionResponse) {
javax.portlet.ActionResponse actionResponse = (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(URL);
}
Have you tried to use RequestDispater instead of response.sendRedirect?
It retains the original request, without changing it.
So, it will remain POST if it was POST.
I have done this by using FORM POST method as follows.
webAppAccess.processPage("importedPage");
Added this imported Page in model :
<HTML>
<HEAD>
<title>New Page</title>
</HEAD>
<Body onload="">
<form id="FormID" method="POST" action="actionURL">
<input type="hidden" name="id" id="ID" value="<%=webAppAccess.getVariables().getString("ID")%>"/>
<noscript>
<p>Your browser does not support JavaScript or it is disabled.
Please click the button below to process the request.
</p>
<input type="submit" value="Proceed " name ="submit"></input>
</noscript>
<script>
document.getElementById('FormID').submit();
</script>
</form>
and then MVC controller mapping as follows:
#RequestMapping(value = {"/Details"}, method = RequestMethod.POST)
public String mthDetails(final Model p_model, #RequestParam(value = "id", required = false) final String p_ID){
//code for further logic using ID
}
In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");
There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example
There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.
You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["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
I have:
<form method="POST" name="f">
<input type="file" name="FileUpload" id="FileUpload" />
</form>
I'm sent the file using ajax,using the uplaod.file method:
document.getElementById('FileUpload').onchange = function() {
file = this.files[0];
ajax = new XMLHttpRequest;
ajax.file = file;
//etc..
ajax.open('post','Default.aspx', true);
ajax.setRequestHeader('foo','baa');
ajax.send(file);
}
Request.Forms["FileUplaod"] // don't works
How I get the value (the file) sent by ajax in my asp.net application?
I tried sent by http headers(is not pratice good,I know) but there problem with long length.
Thanks in advance.
try this form attribute :
form action="some/action" method="POST" enctype="multipart/form-data"
I have a standard aspx page with which I need to add another standard HTML form into and have it submit to another location (external site), however whenever I press the submit button the page seems to do a post back rather than using the sub-forms action url.
A mock up of what the form relationships is below. Note in the real deployment the form will be part of a content area of a master page layout, so the form needs to submit independantly from the master page form.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<form id="subscribe_form" method="post" action="https://someothersite.com" name="em_subscribe_form" >
<input type="text" id="field1" name="field1" />
<input id="submitsubform" type="submit" value="Submit" />
</form>
</div>
</form>
</body>
</html>
It's an interesting problem. Ideally you only want the 1 form tag on the page as other users have mentioned. Potentially you could post the data via javascript without having 2 form tags.
Example taken from here, modified for your needs. Not 100% sure if this will work for you but I think this is how you'll have to approach it.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function postdata()
{
var fieldValue = document.getElementById("field1").value;
postwith("http://someothersite.com",{field1:fieldValue});
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<input type="text" id="field1" name="field1" />
<asp:Button ID="btnSubmitSubscribe" runat="server" Text="Submit" OnClientClick="postdata(); return false;" />
</div>
</div>
</form>
</body>
</html>
If javascript is not a viable option - you can use .Net's HttpWebRequest object to create the post call in code behind. Would look something like this in the code behind (assuming your text field is an asp textbox:
private void OnSubscribeClick(object sender, System.EventArgs e)
{
string field1 = Field1.Text;
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="field1="+field1 ;
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://someotherwebsite/");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
If you add an ASP.NET button to the form, and set its PostBackUrl property to the external site, then all the form data will be posted to that URL.
There is a very nice tricky solution for this problem.
You can insert a </form> tag before your <form> to close the asp.net form which causes the problem. Do not forget to add a <form> tag after your html form. It may cause the editor to give you an exception, but do not worry, it will work.
Nested forms are not possible in HTML according to the W3C. You can achieve your intended result using JavaScript or with jQuery as explained by Peter on a blog called My Thoughts.
In my experience, Appetere Web Solutions has the best solution. Simple and elegant...and it's not a hack. Use the PostBackUrl.
I just tried it and everything works as expected. I didn't want to use Javascript because I didn't want to include it in my Master Page for every page that uses it.
I had the same situation as Ross - except that my input types were all of the "hidden" varitey.
Cowgod's answer got me thinking about nested forms within my .aspx page. I ended up "un-nesting" my 2nd form OUT of the main .aspx form ( ) and placed it (along with my js script tags) just under the body tag - but before the main .aspx form tag.
Suddenly, everything was submitting as it was supposed to. Is this a hack?
ASP.NET allows you to have multiple forms on one page, but only one can be runat=server. However I don't think you can nest forms at all.
You might have to make a new master page, one without a form tag on it so the form will work on that one page only. This is not a good solution, unless you can place the form outside the master pages' form, and use javascript to submit the second form, but that's hardly better. There really is no good solution for what you are trying to achieve, and if so I'd like to hear it. I don't think you can do a POST call from a code-behind, can you? I'm sure there's some way. But that's probably the only solution: from code.