You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:05:17