Reputation: 330
I have a Customer Model containing the following properties: Id, Name and AccountBalance.
A Customer can register an account, but is not able to specify his AccountBalance (I didn't include it in the create method parameter
public ActionResult Create([Bind(Include="Id,Name")] Customer customer)
I added a HiddenFor in the View method:
@Html.HiddenFor(model => model.AccountBalance)
This all works fine, the customer can create an account and the accountbalance defaults to 0.
The problem occurs when editing the customer's account. I don't want the customer to be able to edit his accountbalance, so I also omitted it from the edit method and added a hiddenfor in the edit method's view. When I edit a customer's name for instance, the AccountBalance resets to 0.
How do I deny the user from changing the AccountBalance, but have MVC not reset the value to 0?
Thanks in advance.
Upvotes: 0
Views: 641
Reputation:
Stephen Muecke's first suggestion works for me. Didn't try the second one yet.
On your Controller:
public ActionResult Edit([Bind(Include="Id,Name,AccountBalance")] Customer customer)
Then on your View:
@Html.HiddenFor(model => model.AccountBalance)
Hope this helps and works for others! :)
Upvotes: 1
Reputation: 330
Ended up solving it with Stephen Meucke's suggestion:
var original = db.Customers.FirstOrDefault(x => x.Id == customer.Id);
customer.AccountBalance= original.AccountBalance;
db.Entry(original).CurrentValues.SetValues(customer);
db.SaveChanges();
Thanks a lot!
Upvotes: 0