1

I have a form with some controls .Here I have a checkbox(on the view).In controller I call 2 functions : one for getting saved values and one for saving values. Tis functions works fine , but on my form I have always true , even it in my class I have false.

In controller I have :

return View("Settings", (K.NotificationsSettings)comm.Result);
// comm.Resultset return false form my gfield called Enabled

K.NotificationsSettings is a class which have this structure :

[DataContract] public class NotificationsSettings {

    [DataMember]
    public bool Enabled;                        
    [DataMember]
    public int Interval;                        

}

In my view first line is :

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Child.Master"      Inherits="System.Web.Mvc.ViewPage<K.NotificationsSettings>" %>

and code for this checkbox is :

< input id="Enabled" checked="checked" type="checkbox" name="Enabled" value ="<%=Model.Enabled%>"/>

But my checkbox is always true . Is necessary to put this "=Model.Enabled%>" ? Can somebody help me?

2 Answers 2

1

You should use the appropriate Html helper for checkboxes:

<%: Html.CheckBoxFor( m => m.Enabled ) %>

The helper does something special; it outputs both a checkbox (with value="true") and a hidden input (with value="false"). The reason for this is that a checkbox will not post a value if it's not checked. Only values present in the posted date will be updated in modelbinding so if there is only a checkbox in your html form and you deselect it, the Enabled property is not updated.

Sign up to request clarification or add additional context in comments.

2 Comments

I try to modify like here : <input id="Enabled" checked="checked" type="checkbox" name="Enabled" value ="<%: Html.CheckBoxFor( m => m.Enabled )%>" /> but nothing changed .I try with Model instead m but don't work
You need to replace the entire <input ... /> with the code snippet in my answer. It will generate all the html markup you need.
0

To check a checkbox you have to include the attribute checked with no value:

<input type="checkbox" name="MyCheckbox" value="MyValue" checked>

The value of the attribute value is sent over the wire when you submit the form and the checkbox is checked.

But the better approach would be to use the HtmlHelper like Marnix suggested because that way you don't have to deal with the html creation yourself and you get model binding for free as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.