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")
Related
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
%>
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
I'm studying ASP MVC, and developping SportsStore (Create/Edit feature). When Create a product, Create action will view a Edit view, but when press Sudmit, it call action Create (Post), althrough I will set it call Edit action:
<% using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype="multipart/form-data" }))
{%>
<%--<%= Html.ValidationSummary() %>--%>
<%--<%= Html.Hidden("ProductID") %>--%>
<p>Name: <%= Html.TextBox("Name")%>
<div><%= Html.ValidationMessage("Name")%></div>
</p>
<p>Description: <%= Html.TextArea("Description", null, 4, 20, null)%>
<div><%= Html.ValidationMessage("Description")%></div>
</p>
<p>Price: <%= Html.TextBox("Price")%>
<div><%= Html.ValidationMessage("Price")%></div>
</p>
<p>Category: <%= Html.TextBox("Category")%>
<div><%= Html.ValidationMessage("Category")%></div>
</p>
<p>
Image:
<% if (Model.ImageData == null)
{ %>
None
<% }
else
{ %>
<img src= "<%= Url.Action("GetImage", "Products", new {Model.ProductID}) %>" />
<% } %>
<div>Upload new image: <input type="file" name="file" id="file" /></div>
</p>
<input type="submit" value="Save" />
<%= Html.ActionLink("Cancel and return to list", "Index")%>
<% } %>
Please help me fix it
The code you have seems reasonable if you want it to post back to the Edit action. Your question is a bit confusing, but I'm going to assume that you want to reuse the view and have it post back to Create when rendered from Create and Edit when rendered from Edit. The easiest way is to simply omit the parameters from the BeginForm call. This will cause the form action to be set to the current controller and action, which would give you what you seem to want. An alternative would be to develop templates (display/editor) for the model but have separate views for Create/Edit that simply render the template Html.EditorFor( m => m, "ProductTemplate" ). This would allow you to customize the view -- perhaps the Create view requires you to upload an image? -- yet still reuse most of the code.
I am building a .NET MVC app that has a page with a list of delete buttons, one for each item in a list. The problem I'm having is that the foreach variable "item" is not visible inside the LoginView, which results in the following error:
Compiler Error Message: CS0103: The name 'item' does not exist in the current context
Below is a simplified version of the view. The error occurs at the "new {id=item.Id}" in the LoggedInTemplate - the reference to "item" in the ActionLink works fine:
<% foreach (var item in Model) { %>
<%= Html.ActionLink("Item", "Details", new { id = item.Id })%>
<asp:LoginView runat="server">
<LoggedInTemplate>
<% using( Html.BeginForm( "Delete", "Items", new {id=item.Id}, FormMethod.Post))
{ %>
<input type="submit" value="Delete" runat="server" />
<% } %>
</LoggedInTemplate>
</asp:LoginView>
<% } %>
To clarify the problem is not that the Model has not been successfully passed to the View. The Model is visible from both inside and outside the LoginView. The foreach loop as no problem in iterating through the items in the Model (which is a List). The problem is that the iteration variable "item" is not accessible from within the LoginView - though the original Model is.
Is there any way to pass "item" through to the LoginView's templates? Or is building LoginViews within a foreach loops the wrong way of doing things?
Is there a scoping rule that prevents using local variables within controls - perhaps because the control is rendered at a different time to the main page?
With ASP.NET MVC you really shouldn't use user/custom controls, so if you omit the <asp:LoginView/> and write a line of code to check if the user is authenticated, you are good to go.
Instead of your current code:
<asp:LoginView runat="server">
<LoggedInTemplate>
<div>Show this to authenticated users only</div>
</LoggedInTemplate>
</asp:LoginView>
Just use an if-statement and the value of Request.IsAuthenticated:
<% if (Request.IsAuthenticated) { %>
<div>Show this to authenticated users only</div>
<% } %>
Are you passing the Model to the view and are you also inheriting from the model within that view?
So if this is a View then in your C# code you need to return the list of items like return View(listofitems);
If this is a partial view then <% Html.RenderPartial("MyPartial", listofitems) %>
And in the view you need to
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IQueryable<ListOfItems>>" %>
If all that is in place then it should work no probs.
<% foreach (var item in Model) { %>
<%= Html.ActionLink("Item", "Details", new { id = item.Id })%>
<%= if( Request.IsAuthenticated ) {
using( Html.BeginForm( "Delete", "Items", new {id=item.Id}, FormMethod.Post))
{ %>
<input type="submit" value="Delete" runat="server" />
}
} %>
<% } %>
There is no need to use the LoginView, its not really giving you anything. Use something like the above instead.
Alternatively, you can move the decision of whether to show the delete option for the specific item into the controller, so instead of doing if( Request.IsAuthenticated ) you would do if( item.ShowDelete ) ... assuming item's type is a view model. Another option is to use an extension method for the same, item.ShowDelete(). I prefer the earlier, because there might be logic associated to deciding whether to show delete for a given item, so its better to not have it in the controller or a related logic.
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() : "" ) %>