代码改变世界

关于HtmlHelper.CheckBox()所生成的HTML

2010-01-15 10:34  Rwing  阅读(1023)  评论(1编辑  收藏  举报

不知道大家有没有注意到,在使用HtmlHelper.CheckBox()时会生成如下的HTML代码:

 

<input id="CheckBox" name="CheckBox" type="checkbox" value="true" />
<input name="CheckBox" type="hidden" value="false" />

 

会生成2个input标签,其中一个是hidden的.熟悉HTML的都知道,其实一个input完全够用了.

那么这个hidden起的什么作用呢?翻看ASP.NET MVC的源代码会找到:

// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.

意思就说,如果有多个checkbox,当发送到服务器端时,只会将选中的checkbox的值发送到出去,未选中的checkbox不会发送,这样也就无法得知一共有多少个checkbox以及未被选中的checkbox的值了.增加的这个hidden就是起这个作用的.

那么追求完美的人(或者称之为变态...例如我...)就希望只生成一个checkbox的input就好了,ok,那么让我们自己动手来扩展一个NewCheckBox吧

(代码就不贴了,很容易写出来)......

当仅仅使用1个input的时候,你会发现在Controller中会接收不到这个bool值

例如

<%= Html.NewCheckBox("isChecked")%>

...

public ActionResult Index(bool isChecked){}

这时isChecked是接收不到的,因为这时checkbox post到服务器的值是ON或空(或value不为空则为value值,参见html基础),自然也就无法转换成bool了,ok,那也容易解决,自己建立一个ModelBinder就好了

 

public class CheckBoxModelBinder : IModelBinder
{
    
#region IModelBinder Members

    
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value 
= controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
        
return string.IsNullOrEmpty(value) || value.Equals("FALSE", StringComparison.OrdinalIgnoreCase) ? 
            false : true;
    }

    
#endregion
}

 

然后在建立相应的Attribute

 

public class CheckBoxAttribute : CustomModelBinderAttribute
{
    
private static CheckBoxModelBinder _modelBinder = new CheckBoxModelBinder();

    
public override IModelBinder GetBinder()
    {
        
return _modelBinder;
    }
}

 

 再修改Action加上这个Attribute

public ActionResult Index([CheckBox]bool isChecked){}

OK,完成

 

后记:其实2个input完全可以接受,就多那么几个字节..不过变态嘛