Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 690
Mark Avatar asked Jul 03 '13 21:07

Mark


1 Answers

@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.

like image 87
Stan Avatar answered Sep 19 '22 16:09

Stan