如何合并仅HtmlAttributes不同的MVC Helper?尝试三元表达式失败
当然可以合并,给你两种简单的实现方式:
方式一:分步构建控件对象
先把两个分支里重复的配置抽出来,再根据条件添加差异的HtmlAttributes:
@{ // 先初始化基础的RadioGroup配置 var radioGroup = Html.Kendo().RadioGroupFor(m => m.MeetingPollingQuestions) .Name(string.Format("PollingResponses[{0}].Value", idx)) .Items(i => { foreach (var option in item.RadioButtonList) i.Add().Label(option.Label).Value(option.Value); }) .Value("Value"); // 根据必填条件追加HtmlAttributes if (item.isRequired) { radioGroup = radioGroup.HtmlAttributes(new { required = "required", data_val_required = "Question is Required" }); } } @radioGroup
方式二:链式调用里用三元表达式
直接在HtmlAttributes方法中通过三元表达式动态传递参数,一步完成配置:
@(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") )
之前你尝试的写法没生效,大概率是三元表达式的语法或者参数传递有误,上面两种写法都能完美合并重复代码,保留差异逻辑。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

