简体   繁体   中英

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?

ie. if I use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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