Reputation: 11
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"
}
Upvotes: 0
Views: 2782
Reputation: 2660
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")
Upvotes: 0
Reputation: 1039398
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
.
Upvotes: 1
Reputation: 5550
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.
Upvotes: 0