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.

7
  • 1
    What would be the point? Commented Oct 18, 2014 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? Commented Oct 18, 2014 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. Commented Oct 18, 2014 at 12:07
  • @AntP, If all properties of the model are hidden? What is there to validate? Commented Oct 18, 2014 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). Commented Oct 18, 2014 at 12:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.