ASP.NET用户控件Nullable<bool>属性赋值null报错求助
解决ASP.NET用户控件可空Bool属性设为Null的报错问题
咱先搞明白为啥会报错:ASP.NET Web Forms的默认属性转换器认不出字符串null或者空串是bool?类型的null值,它会硬着头皮尝试把字符串转成普通bool,自然就抛出类型转换错误了。给你几个靠谱的解决办法:
方法1:后台代码初始化(最直接)
别在前台ASCX/ASPX里设置State属性,直接在后台代码的合适时机(比如Page_Load或者控件的OnInit事件)赋值:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { wucSwitchButton3States.State = null; } }
这个方法完全绕开了前台的类型转换问题,简单粗暴还不容易出问题。
方法2:自定义类型转换器(适合需要前台配置的场景)
如果必须在前台设置State="null"或者空串,那可以给State属性加一个自定义类型转换器,让ASP.NET能正确识别并转换。
首先创建转换器类:
using System; using System.ComponentModel; using System.Globalization; public class NullableBoolConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { // 允许从字符串类型转换 return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; // 空串、空白串或者"null"字符串都转成null if (string.IsNullOrWhiteSpace(strValue) || strValue.Equals("null", StringComparison.OrdinalIgnoreCase)) { return null; } // 其他情况正常转bool return bool.Parse(strValue); } }
然后给你的State属性加上TypeConverter特性:
[TypeConverter(typeof(NullableBoolConverter))] public bool? State { get; set; }
这样前台写State="null"、State=""甚至State=" "都能正确转成bool?的null值了。
方法3:使用正确的数据绑定表达式
你之前用的<%=null%>是输出表达式,它会把null渲染成字符串"null"输出到页面,而不是把null赋值给属性。要使用数据绑定表达式<%# null %>,然后记得在后台调用DataBind():
前台写法:
<uc1:wucSwitchButton3States runat="server" State="<%# null %>" ID="wucSwitchButton3States" />
后台在Page_Load里调用:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // 触发数据绑定 this.DataBind(); // 或者单独给控件绑定:wucSwitchButton3States.DataBind(); } }
这个方法需要注意数据绑定的时机,必须在控件初始化完成后调用,否则可能不生效。
内容的提问来源于stack exchange,提问作者Muhammad Musavi
相关产品推荐
相关产品推荐

