HTML.TextBox中的动态属性
问题描述:
我试图用条件属性来构建TextBoxFor。HTML.TextBox中的动态属性
如果Model.question没有CALC_EXPRESSION,我甚至不想显示数据公式属性。
这可能吗?这不起作用:
@Html.TextBoxFor(q => question.AnswerFloatString,
new
{
Value = "",
id = String.Concat("Percent_of_Funding_", i.ToString()),
Name = "QuestionBasicSection.Questions[" + question.Index+ "].AnswerFloatString",
@class = "form-control percentMask",
data_bind = "textInput: sdto.DATE_INACTIVE",
data_pattern = question.FORMAT_VALIDATION,
data_cell = "F" + (15 + i).ToString(),
data_format = (question.FORMAT_VALIDATION == "pecent" ? "0.00%" : (question.FORMAT_VALIDATION == "currency" ? "$0,0.00" : "")),
(question.CALC_EXPRESSION.Trim() != "" ? data_fomula = question.CALC_EXPRESSION:""),
@readonly = "readonly",
tabindex = "-1"
})
但是,如果我这样做:
data_fomula = (question.CALC_EXPRESSION.Trim() != "" ? question.CALC_EXPRESSION:""),
我得到和在HTML空属性,如果在模型中没有CALC_EXPRESSION,我得到一个“对象引用没有设置“例外。 如果question.FORMAT_VALIDATION!='percent'或'currency',我也不会介意不具备数据格式属性。
答
Html.TextboxFor以IDictionary作为参数来填充文本框的html属性。
您应该创建基于你的逻辑填充所有属性的字典,然后通过这个字典到textboxfor方法。
通过这种方式,您可以更好地控制哪个属性会出现或不出现什么值。
var attributes = new Dictionary<string,object>();
attributes.Add ("id", String.Concat("Percent_of_Funding_", i.ToString()));
// and so on.... keep adding the attributes based on the logic.
//Have an if block for adding certain attribute only if certain condition is met.
//That way you will not have the unnecessary attributes.
@Html.TextBoxFor(q => question.AnswerFloatString, attributes)
答
后一种方法,你应该怎么做,但是你想从三元,而不是一个空字符串,即:
data_fomula = (question.CALC_EXPRESSION.Trim() != "" ? question.CALC_EXPRESSION : null),
属性,这些属性是空的,不包含在生成的HTML返回null
。