error with form action - asp.net

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.

Related

Not able to post form in Adode CQ5

I am a newbie in AdobeCQ5. I am facing some trouble in posting form. Here is my Structure -
/apps/<myproject>/components/mytestcomponent
mytestcomopnent.jsp has following code -
<form id="myForm" action="<%=resource.getPath()+".html" %>">
<input type="text" id="t1" class="input-small" placeholder="Temprature F" />
<input type="text" id="t2" class="input-small" placeholder="Temprature C" readonly/>
<button type="button" id="cbtn" class="btn">Convert</button>
</form>
<script>
$(document).ready(function() {
$('#cbtn').click(function () {
var URL = $("#myForm").attr("action");
alert(URL);
var t1=$("#t1").val();
var t2=$("#t2").val();
$.ajax({
url: URL,
data:{'t1':t1},
type:"post",
success: function(data, status) {
$("#t2").val(data);
},
error: function( xhr, txtStat, errThrown ) {
alert("ajax error! " + txtStat + ":::" + errThrown);
}
});
});
});
</script>
This is giving my response code 200 (Success) but the output is not desired. My mycomponent.POST.jsp has following code -
<%
// TODO add you code here
String t1=request.getParameter("t1");
%>
<%= t1 %>
It gives the following output
Content modified /content/imobile/en/jcr:content/social.html
Status
200
Message
OK
Location /content/imobile/en/_jcr_content/social.html
Parent Location /content/imobile/en/_jcr_content
Path
/content/imobile/en/jcr:content/social.html
Referer http://example.comt:4502/content/imobile/en.html
ChangeLog
<pre></pre>
Go Back
Modified Resource
Parent of Modified Resource
Please help to resolve this.
The JSP file handling the POST method for your component should be named POST.jsp rather than mycomponent.POST.jsp.
Please notice that if you intercept all POST requests to your component, you won't be able to edit it on the author instance using a dialog (as the dialog simply POSTs data to the component URL). To avoid it, consider using a custom selector (like form). Your form should look be declared like this:
<form id="myForm" action="${resource.path}.form.html">
and the script handling POST request should be called form.POST.jsp.
The second important thing is that you should use Java classes rather than JSP files to store business logic. In this case it means that the form.POST.jsp script can be replaced with a Sling servlet declared as follows:
#SlingServlet(
resourceTypes="myproject/components/mytestcomponent",
methods="POST",
selectors="form")

Create form action as variable

I have t following ASPX source :
<form name="AddComment" action="ViewArticle.aspx?ArticleID=<%=ArticleID %>" method="post" runat="server">
The problem is that when I click submit I got this url
http://localhost:61175/WebSite1/ViewArticle.aspx?ArticleID=%3C%=ArticleID%20%%3E
But I want get this URL :
http://localhost:61175/WebSite1/ViewArticle.aspx?ArticleID=1
If I delete the "runat="server"" command it works fine, but can this form work with the
variable and the runat server at the same time?
Maybe you can try setting the action just before the form markup like this (or in codebehind, at your choice)
<%
this.Form.Action = "ViewArticle.aspx?ArticleID=" + ArticleID.ToString();
%>
<form name="AddComment" method="post" runat="server">
In server side controls you can't do such things as <%= ActionID %> you can only bind <%# ActionID %>.
The upper solution won't work, becouse the form is not that form. You have to give a control ID + name than setup the post url. If it's not an option you can dinamicly search for form item in the control tree, so dynamic ID-s can be handled.

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

How to pass value from asp to aspx

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

Using embedded standard HTML forms with ASP.NET

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.

Resources