How to pass value from asp to aspx - asp.net

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

Related

How to Send Post request in java with javax.portlet.ActionResponse.sendRedirect method?

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
}

Forward and pass data along in Asp.net

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"]);

error with form action

I have the following C# code:
AddCommentForm = string.Format("<form name=\"AddComment\" method=\"post\" runat=\"server\" id=\"add_comment_form\"><p> TITLE: <input type =\"text\" name=\"Title\" /></p><p> Contnt <textarea name=\"Content\" ></textarea></p><p> <button type=\"submit\">Submit!</button></p></form>");
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID;
The problem is that there is an error in the second line:
System.NullReferenceException was caught
My question is how can I this error?
And why with this code it works?
<%
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID.ToString();
%>
<form name="AddComment" method="post" runat="server">
AddCommentForm = string.Format("<form name=\"AddComment\" method=\"post\" ....
Above code is not valid. AddCommentForm is a HtmlForm control - not a string. Besides, you cannot create another form tag inside a form in ASP.Net.
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID.ToString();
Basically, you are Cross-Site Scripting. Although it compiles, it won't work. When you get to ViewArticle.aspx page, you'll get an error.
If you want a form inside ASP.Net, use iframe.

How do I resolve "Object reference not set to an instance of an object" error?

I am passing the following via the request object in codeBehind:
Get the Requested code to be created.
Dim Code As String = Request("code").ToString()
and below is my markup page called barcodes.aspx:
<form id="Form1" method="post" runat="server">
<img src="barcodes.aspx?code=XXXXX" alt="barcode" />
<asp:Image id="myBarCode" runat="server"></asp:Image>
</form>
Why am I getting the error above?
If Request("code") is null, calling .ToString() on it will give you a null reference exception.
Check if Request("code") is null or not. If it is null, then you will get an object reference error when calling ToString()
I think this has to deal with the fact that you are trying to get the query string value of an image on the page. Request() will only get the querystring for the 'requested page', which is the page you are on, not the image itself. Therefore your code will always be null if you are expecting it to pull from the image source
You need to actually submit the form (POST) or pass the parameters in the URL (GET) to get the request parameters via the Request object. Two easy ways (of many) to do this:
Option 1. Keep just your barcodes.aspx and barcodes.aspx.vb. In barcodes.aspx put:
<form id="Form1" method="post" runat="server">
<input type="hidden" name="code" value="XXXXX" />
<asp:Image id="myBarCode" runat="server"></asp:Image>
<asp:Button runat="server" Text="Submit"></asp:Button>
</form>
In barcodes.aspx.vb put in the Page_Load:
If PostBack Then
Dim code As String = Request.Form("code")
If Not String.IsNullOrEmpty(code) Then
' Generate your image here, a code has been specified
End If
End If
Then just hit the submit button on your aspx page.
Option 2. Split it into two aspx pages but basically same as above.
In submitme.aspx put this (for a POST, click the button):
<form id="Form1" method="post" runat="server">
<input type="hidden" name="code" value="XXXXX" />
<asp:Button runat="server" Text="Submit" PostBackURL="barcodes.aspx"></asp:Button>
</form>
Or this (for a GET, click the link):
Click Me
In barcodes.aspx.vb put this in Page_Load (works for either the GET or POST option):
Dim code As String = Request("code")
If Not String.IsNullOrEmpty(code) Then
' Generate your image here, a code has been specified
End If
In barcodes.aspx you would then simply need:
<asp:Image id="myBarCode" runat="server"></asp:Image>
You can simply remove ToString(), as Request(item key) returns String:
Dim Code As String = Request("code")
Check to see that the query string value exists:
Dim Code as String = String.Empty
If Not Request.QueryString("code") Is Nothing Then
Code = Request.QueryString("code")
End If
You could also use the string.isnullorempty() function to test the contents of the request.querystring value

POST data getting 'lost' somewhere

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);

Resources