开发者

ASP.net MVC and checkboxes

Hi,

I know that its possible to use Html.CheckBoxFor(c=>c.MyBool) to get the default binder to bind correct value to an model object parameter in an control action(strong typed view).

If I however need to add a "rememberme" checkbox in a form on the masterpage, this will mean that there is no strong type to use.

Say that the Logon action takes a object of the following class

public class LogOnModel
    {
        [Required]
        [DisplayName("User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }

        [DisplayName("Remember me?")]
        public Boolean RememberMe { get; set; }
    }

To get the default binder to map to UserName and Password we could just create inputs that has the correct names (UserName/Password). This is however not possible with the RememberMe prope开发者_开发百科rty. To get this working I hade to ad a hidden field with the name RmemberMe and then set this input with a javascript like this :

$(document).ready(function () {

            $('input[id*=chkbRemember]').click(function () {
                if ($('input[id*=chkbRemember]').attr('checked')) {
                    $('input[id *= RememberMe]').val("True");
                }
                else {
                    $('input[id *= RememberMe]').val("False");
                }
            });
        });

This will work but is it really the right way?

BestRegards


This is a well-known issue with HTML forms.

If you have a checkbox input, and it is never checked, the value is not posted.

Html.CheckBox & Html.CheckBoxFor render an additional hidden element with the same name to ensure that some value always gets posted. I believe Ruby on Rails uses the same technique (and possibly others).

There's a short discussion on the Asp.Net forum about this, as well as some previous StackOverflow questions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜