When is Request.Form["name"] null and when an empty string? - asp.net

Why do the following result in a true if clause even though the textbox is empty and not even touched on a postback? :
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] != null) // Prints out "Name OK" on postback.
{
Response.Write("<br/>");
Response.Write("Name OK");
}
%>
Does the textbox actually contain an empty string ("") on a postback?
Why do the following result in a true if clause on the first page load but not on a postback? :
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] != "") // Prints out "Name OK" on first page load, but not on postback.
{
Response.Write("<br/>");
Response.Write("Name OK");
}
%>
To get a successful and expected result I have to use the following:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>
<%
if (Request.Form["name"] != null && Request.Form["name"] != "")
{
Response.Write("<br/>");
Response.Write("Name OK");
}
%>

First, let me answer your question:
The first page load is a GET, postbacks are a POST (hence the name postback). Request.Form is populated only if the page is loaded though a form POST.
On the first page load, Request.Form is an empty collection. Since Request.Form is a NameValueCollection, accessing a non-existent entry returns null. Thus, Request.Form["whatever"] returns null on the first page load.
After a postback, Request.Form is filled with values. Since HTTP POST does not know about null values, Request.Form["whatever"] returns an empty string for fields which are present but empty.
If you want to avoid the x != null && x != "" pattern, use String.IsNullOrEmpty or the null coalescing operator: (x ?? "") != "".
On the other hand, you could make your life a lot easier by just using the built-in WebForms features instead of parsing Request.Form yourself:
<form runat="server">
<asp:TextBox ID="nameBox" runat="server" />
<asp:Button Text="Do Postback" runat="server" />
</form>
<%
if (nameBox.Text != "")
{
%><br />Name OK<%
}
%>
Since TextBox.Text defaults to "", there's no need to check for null here.

Request.Form is NameValueCollection, which returns null if specified key is not found, returns value (which is an empty string) otherwise.
You may use string.IsNullOrEmpty() method.
if (!string.IsNullOrEmpty(Request.Form["name"]))
{
Response.Write("<br/>");
Response.Write("Name OK");
}

Request.Form["ControlName"] returns null if Control is not present on form.
If Control is present, but it contains null or empty value, then Request.Form["ControlName"] will always return String.Empty.
So it's good practice, instead of comparing (Request.Form["ControlName"] != null), use (!String.IsNullOrEmpty(Request.Form["ControlName"]))

Base on this site: https://www.mikesdotnetting.com/article/293/request-form-is-empty-when-posting-to-aspx-page
This is the answer. Remark this line:
settings.AutoRedirectMode = RedirectMode.Permanent;
in routeConfig.cs

Related

Checkbox boolean value Classic ASP

I have a checkbox
<input type="checkbox" name="chkNGI" id="prod_ngi_sn" value="1">
When it is checked I pass the value 1, but when it is not checked any value is passed.
I have to pass the value 0.
I've tried
<input type="checkbox" name="chkNGI" id="prod_ngi_sn" <%if prod_ngi_sn.checked then value="1" else value="0" end if%>>
But didn't work.
tks
Checkboxes only pass values when ticked. You need logic on the server side to accommodate that.
Dim chkNGI
chkNGI = Request("chkNGI") & ""
If chkNGI = "" Then
chkNGI = "0"
End If
<script>
function calcParam() {
var checked = document.getElementById("prod_ngi_sn").checked;
if (checked)
document.getElementById("hiddenNGI").value = "1";
else
document.getElementById("hiddenNGI").value = "0"; }
</script>
<input type="hidden" name="chkNGI" id="hiddenNGI">
<input type="checkbox" name="checkNGI" id="prod_ngi_sn" onClick="calcParam()">
You can try this single line solution
Information: RS=Recordset Object
<input type="checkbox" <%If RS("ColumnName")=True Then Response.Write(" checked='checked' ")%> name="tableColumn" value="1" >
I know this question is old, but I recently had to refactor some legacy code for a company in Classic ASP, and ran into this problem. The existing code used a hidden form field with the same name as the checkbox and looked for either "false" or "false, true" in the results. It felt kludgy, but the code also performed actions based on dynamically named checkbox fields with prefixes, so inferring "false" from a missing field would introduce different complications.
If you want a checkbox to return either "0" or "1", this technique should do the trick. It uses an unnamed checkbox to manipulate a named hidden field.
<html>
<body>
<% If isempty(Request("example")) Then %>
<form>
<input type="hidden" name="example" value="0">
<input type="checkbox" onclick="example.value=example.value=='1'?'0':'1'">
<input type="submit" value="Go">
</form>
<% Else %>
<p>example=<%=Request("example")%></p>
<% End If %>
</body>
</html>
Create a hidden input with the name "chkNGI".
Rename your current checkbox to something different.
Add handled for onClick on the checkbox and using a small javascript function, depending on the state of the checkbox, write 0 or 1 in the hidden input.
As an example,
<script>
function calcParam() {
var checked = document.getElementById("prod_ngi_sn").checked;
if (checked)
document.getElementById("hiddenNGI").value = "1";
else
document.getElementById("hiddenNGI").value = "0";
}
</script>
<input type="hidden" name="chkNGI" id="hiddenNGI">
<input type="checkbox" name="checkNGI" id="prod_ngi_sn" onClick="calcParam()">
Your solution in post to saving page;
save.asp
<%
' connection string bla bla
' RS = Recordset Object
If Request.Form("tableColumn")=1 Then
RS("ColumnName") = 1
Else
RS("ColumnName") = 0
End If
' other columns saving process bla bla bla
%>

Get the Value of a checkBox server Side

i want to get the value of a checkbox... my Checkbox show the Value of the Database "true" or "false" and the user can change the Value (if he dont like it)
i get every time the Value false
View:
<%if ((Boolean)ViewData["Statistik3"])
{%>
<input type="checkbox" name="Statistik3" value="true" checked= "checked"/>
<%}
else
{ %>
<input type="checkbox" name="Statistik3" value="false"/> <%--</input>--%>
<%} %>
Controller C#
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Formular(string button, string decision1, FormEntries entries )
{
entries.Statistik3 ? "Yes" : "No"
}
Try rendering the checkbox using a server side Html helper. Don't hardcode input elements as you did in your views because this leads to horrible spaghetti code. So replace the entire code you have shown with a simple call to the Html.CheckBox helper which will take care of rendering the proper input element:
#Html.CheckBox("Statistik3")
and now the controller action you are posting to could take a boolean argument with the same name:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Formular(bool statistik3, string button, string decision1, FormEntries entries)
{
// you could use the statistik3 boolean argument to determine
// whether the user checked or not the checkbox
}
The next improvement I would do would be to completely get rid of ViewData and define a view model that will contain all the information this view requires and then use the strongly typed version of the helper: Html.CheckBoxFox.
Checkboxes are boolean only types; the value attribute will be ignored and it's only where there is the presence of the absence of the checked attribute. Is you form bound to a data model at all? Try the following:
<%if ((Boolean)ViewData["Statistik3"])
{%>
<input type="checkbox" name="Statistik3" id="Statistik3" checked="checked"/>
<%}
else
{ %>
<input type="checkbox" name="Statistik3" id="Statistik3"/> <%--</input>--%>
<%} %>
and then test for a boolean value on return.
Hope that helps.
you need to make sure the Checkbox is wrapped within a form element. Something like this
<% using(Html.BeginForm("Formular")){
<%if ((Boolean)ViewData["Statistik3"])
{%>
<input type="checkbox" name="Statistik3" value="true" checked= "checked"/>
<%}
else
{ %>
<input type="checkbox" name="Statistik3" value="false"/> <%--</input>--%>
<%} %>
<%} %>
As suggested above, you should be using #Html.CheckBox("Statistik3")

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

Check if submit IMAGE was clicked via Request.Form

How do I check if a submit IMAGE was clicked via Request.Form?
The following checks if a submit BUTTON was clicked via Request.Form by returning the value of the submit button if clicked:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="submit" id="submit" value="Submit!" runat="server" />
</form>
<%
if (Request.Form["submit"] != null) //TRUE
{
Response.Write("Submit button pushed");
}
Response.Write(Request.Form["submit"]); //Returns "Submit!"
%>
The following checks if a submit IMAGE was clicked via Request.Form, but it DOESN'T return any value after the image was clicked:
<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="image" id="subimg" src="solar_image.gif" alt="Can't show image" value="Submit Image!" runat="server"/>
</form>
<%
if (Request.Form["subimg"] != null) //FALSE
{
Response.Write("Image Submit button clicked!");
}
Response.Write(Request.Form["subimg"]); //Doesn't return "Submit Image!"
%>
The above code works for me in IE 9 and Chrome. Only way I can replicate is when using the Firefox as a browser.
This link sheds more light on the issues Firefox 4.0 beta — as well as IE and Opera — do not send name/value for input type=”image”; only .x and .y coordinates are sent.
The following check works in every browser I've tested:
//Checking both x and y co-ordinates to be doubly safe
Request.Form["subimg.x"] != null && Request.Form["subimg.y"] != null
According to the MDN documentation:
"Gecko 2.0 only sends x and y coordinates when clicked, not longer the
name/value of the element"
Try printing out Request.Form. If there's x and y in the response, you can detect that an image was clicked that way instead.

ASP.NET MVC: set value in other field on my view, how to?

I have a view where the user can change some settings, its basically a "edit" page. When the user checks a particular value in a radio group i set a hidden field (its a invisible input type=text field), but when i load the page i want that hidden field set from my code. How to do this? JQuery? or can i "findControl" somehow?
This is the "hidden" field:
<div style="display: none">
<input type="text" name="HiddenImageId" id="HiddenImageId" value="" />
</div>
The above hidden field is set from a jquery that executes when a radio-button is clicked. But when I load in "edit" mode I want myself to set the "hidden" field.
Further down my view i load all the radio-buttons:
<% if (file.Id == imageFile.Id)
{ %>
<input type="radio" checked="checked" name="filename" class="filename" id="<%= file.Id.ToString()%>" />
<% }
else
{ %>
<input type="radio" name="filename" class="filename" id="<%= file.Id.ToString()%>" />
<%} %>
When I set the checked attribute I want to set the value of my hidden fiddle to the files ID.
You would probably benefit a lot from making better use of the [Html Helpers] in ASP.NET MVC.
You could, for example, output your "hidden" text input like this:
<%= Html.TextBox("HiddenImageId", imageFile.Id) %>
If imageFile can be null, you might want to add a check for that - use shorthand if to make it look nice:
<%= Html.TextBox("HiddenImageId", imageFile != null ? imageFile.Id : "") %>
You could also probably improve your code for the radiobuttons significantly by using Html.RadioButton...
just like you are doing
id="<%= file.Id.ToString()%>"
you can do
<input type="text" name="HiddenImageId" id="HiddenImageId" value="<%= file.Id.ToString()%>" />
or whatever the code is to get your value
I'd suggest using the HtmlHelper extensions in both cases.
<div style="display: none">
<%= Html.TextBox( "HiddenImageId",
file.Id == imageFile.Id ? file.Id.ToString() : "" ) %>
</div>
<%= Html.RadioButton( "filename",
"",
file.Id == imageFile.Id,
new { #class = "filename", id = file.Id.ToString() } ) %>
or if you wanted to use a hidden input instead, skip the invisible DIV, and use
<%= Html.Hidden( "HiddenImageId",
file.Id == imageFile.Id ? file.Id.ToString() : "" ) %>

Resources