简体   繁体   English

ASP.Net MVC将标签值回发给控制器

[英]ASP.Net MVC Postback a label value to your controller

When using an EditorTemplate, if I want a value on the model to be displayed on the screen, but also to be posted back to the controller, what helper should I use? 使用EditorTemplate时,如果我希望模型上的值显示在屏幕上,还要发布回控制器,我应该使用什么帮助器?

ie. 即。 if I use TextBoxFor: 如果我使用TextBoxFor:

@Html.TextBoxFor(model => model.RoomTypeName)

...then the user can amend the text... ...然后用户可以修改文本...

I would rather just show the text, but if I use: 我宁愿只显示文字,但如果我使用:

@Html.DisplayTextFor(model => model.RoomTypeName)

...then that is not posted back to the controller. ...然后不会回发给控制器。

So is the only way I can display the text, and also to ensure my model state is valid, to add a second hidden field, eg: 因此,我可以显示文本的唯一方法,也是为了确保我的模型状态有效,添加第二个隐藏字段,例如:

@Html.DisplayTextFor(model => model.RoomTypeName)
@Html.HiddenFor(model => model.RoomTypeName)

I know that works, but I'm wondering if there is a more elegant way of doing it - so I can display the value, and post it back, without the need to replicate it as a hidden element also? 我知道这有效,但我想知道是否有更优雅的方式 - 所以我可以显示值,并将其发回,而不需要将其复制为隐藏元素?

Thank you, 谢谢,

Mark 标记

@Html.DisplayTextFor(model => model.RoomTypeName)
@Html.HiddenFor(model => model.RoomTypeName)

This is very clean and standard way of doing what you want to achieve. 这是做你想要达到的目标的非常干净和标准的方式。

If you would make your own HTML helper that does exactly the same thing it by saving one line would just confuse other people who might read your code in the future, or even yourself. 如果您要创建自己的HTML帮助程序,它完全相同,那么通过保存一行就会混淆将来可能会读取您的代码的其他人,甚至是您自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM