mishap
mishap

Reputation: 8515

Preserving a model property

I have a view rendering a Model, where Model is changed and posted to an action. Some properties of the Model are kept unchanged and just need to be passed on to the view. Eg. Model has properties Color and Name:

**View:**
Model.Name - used for for something.
Model.Color - not used, just needs to be preserved and passed on to action.

[HttpPost]
**Action:**
String Name = Model.Name
String Color = Model.Color

Do I use a hidden field for that ?

Upvotes: 2

Views: 208

Answers (2)

Steve Wilkes
Steve Wilkes

Reputation: 7135

I solved this issue using ViewModel builders, which I've written a blog on. As @dknaack says, anything which comes in a request can be manipulated by users, so to ensure my non-editable model properties retain the correct values, I created builder classes which just over-write non-editable values with the appropriate values from the database. This is much cleaner and more secure than using hidden fields in my opinion.

Upvotes: 0

dknaack
dknaack

Reputation: 60486

Yes, but only if Color can be different on different requests and you need that value after the post.

Another way is to store it in the Session.

The safer way is to store it in the session, because even hidden fields can be manipulated

Hidden

@Html.HiddenFor(x => x.Color)

Session

Session["YourKey"] = Color;

Upvotes: 1

Related Questions