Kendo RadioGroupFor基于布尔值设置HtmlAttributes失效问题
问题分析与解决方案
你遇到的问题核心是**HtmlAttributes方法接受的是对象类型,而非字符串**。你把匿名对象的定义写成字符串赋值给htmlAttributesData,但Kendo的HtmlAttributes无法将字符串解析为有效的属性集合,所以必填属性不生效;而直接传入new { ... }时,传递的是实际的匿名对象实例,方法能正确识别并渲染属性。
正确实现方式
方式一:直接在HtmlAttributes中使用三元表达式
不需要额外变量,直接在方法内根据item.isRequired生成对应对象:
@(Html.Kendo().RadioGroupFor(m => m.MeetingPollingQuestions) .Name(string.Format("PollingResponses[{0}].Value", idx)) .HtmlAttributes(item.isRequired ? new { required = "required", data_val_required = "Question is Required" } : new { }) .Items(i => { foreach (var option in @item.RadioButtonList) i.Add().Label(option.Label).Value(option.Value); }) .Value("Value") );
方式二:提前定义对象变量
如果需要复用这个逻辑,可以提前创建对象类型的变量(而非字符串):
var htmlAttributesData = item.isRequired ? new { required = "required", data_val_required = "Question is Required" } : (object)new { }; @(Html.Kendo().RadioGroupFor(m => m.MeetingPollingQuestions) .Name(string.Format("PollingResponses[{0}].Value", idx)) .HtmlAttributes(htmlAttributesData) .Items(i => { foreach (var option in @item.RadioButtonList) i.Add().Label(option.Label).Value(option.Value); }) .Value("Value") );
注意这里要把默认值强制转为object,避免编译器推断类型不一致的问题。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

