2

Is there a way to render a complete model as hidden fields?

Something like:

@Html.HiddenFor(m => m)

Or do I have to render every single property of my model with HiddenFor?

Edit:

It is a complex wizard (5-10 steps). In the last step I want to store the data in the DB. Perhaps I can serialize the model as JSON to a hidden field. Then I could also access it via JS.

G-Wiz
  • 7,370
  • 1
  • 36
  • 47
LuckyStrike
  • 1,483
  • 3
  • 12
  • 23
  • 1
    What would be the point? –  Oct 18 '14 at 12:01
  • you can make a type of T Generic model and then use an EditorFor or DisplayFor template and use reflection to iterate through the properties of the model and render it as a hidden field. Something like this would work. However I agree - what would be the point? – Ahmed ilyas Oct 18 '14 at 12:02
  • @StephenMuecke I presume the point is to be able to re-render non-editable model properties when, for example, form validation fails and model errors are being displayed. – Ant P Oct 18 '14 at 12:07
  • @AntP, If all properties of the model are hidden? What is there to validate? –  Oct 18 '14 at 12:10
  • @StephenMuecke Ignoring the fact that hidden fields still need to be validated server side, that's not what I mean - suppose you have a view that displays 5 property values and allows you to edit two property values. If server-side validation fails, the typical solution is to do this: `if(!ModelState.IsValid) return View(model)`. If you haven't persisted those 5 display-only properties via hidden fields or some other mechanism, the returned view can't display them (without fetching them all from the DB again). – Ant P Oct 18 '14 at 12:19
  • @AntP, I agree if there are some properties which are being edited, but OP has indicated hidden fields for the **complete** model which suggests there is no editing –  Oct 18 '14 at 12:24
  • [This answer](http://stackoverflow.com/questions/6402628/multi-step-registration-process-issues-in-asp-net-mvc-splitted-viewmodels-sing/6403485#6403485) may offer some guidance. –  Oct 18 '14 at 12:33

1 Answers1

2

Well you could serialize the object to a string of some format, such as XML or Base64, and put that into a hidden field, but that is basically just old-school ASP.NET ViewState.

If you are only editing a couple of fields in a large object, it is generally better to just have the ID on the page (in a hidden field or the URL) and reconstruct it again from the database/session/wherever when they submit the form.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • It is a complex wizard (5-10 steps). In the last step I want to store it in the DB. Perhaps I can serialize the model as JSON to the hidden field. Then I could also access it via JS. – LuckyStrike Oct 18 '14 at 12:21