TextBoxFor @Value (uppercase) instead @value

对着背影说爱祢 提交于 2020-01-01 04:55:09

问题


This is just for curiosity

Why does this code work:

Html.TextBoxFor(x => x.Age, new { @Value = "0"})

and this doesn't:

Html.TextBoxFor(x => x.Age, new { @value = "0"})

Note the uppercase 'V' in @Value

I know value is a keyword, but so is readonly and it works. It's not necessary to use @Readonly (with uppercase 'R').

Does anybody have a clue?


回答1:


I'm not 100% sure but, that could be value is a keyword in properties, readonly isn't. Look at properties from MSDN.




回答2:


InputExtensions.TextBoxFor special cases cases a few attribute names, among them value(case sensitive). This is unrelated to C# keywords.

In particular the value obtained from the expression parameter takes precedence of a property called value you pass into the htmlAttributes parameter.

Taking a look at your example:

  • If you use Html.TextBoxFor(x => x.Age, new { @value = "0"}) it will compile, but TextBoxFor will override the value attribute with the value x.Age evaluates to.

  • If you use Html.TextBoxFor(x => x.Age, new { @Value = "0"}) it will compile, and you will get two entries in the attribute dictionary, one Value that's "0", and one value, that's x.Age.

    I expect the output to be something nonsensical like <input Value="0" value="..." type="text"/>.




回答3:


My guess is that the MVC code is hard coded to look for Value because a MS engineer intended you to always use PascalCase property names, since that's their typical convention and PascalCase avoids conflicts with non-contextual keywords such as class. Notice how PascalCase properties get rendered in the HTML as lowercase.

The reason is not about value being a keyword, since it's a contextual keyword in C# and only has special meaning (and thus turns blue in the IDE) in property getters and setters. It has no special meaning in the anonymous type passed to TextBoxFor.



来源:https://stackoverflow.com/questions/14142511/textboxfor-value-uppercase-instead-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!