Percy
Percy

Reputation: 3115

Entity Framework saving a property with [ReadOnly(true)] Metadata

MVC 5 EF 6. I've created an edit page using Scaffolding. Saving works fine until I want to restrict the editing of certain properties.

I didn't just use:

@Html.HiddenFor(model => model.Property)

as I wanted the fields to still be visible in the UI. and I didn't want to make it uneditable in the view as it's not really MVC - I wanted to control the editing of the Property from the Model (this is a field that should NEVER be changed but isn't the primary key).

I've implemented the solution from here: How to create readonly textbox in ASP.NET MVC3 Razor and it works perfectly. I can use the annotation:

[ReadOnly(true)]

on my Properties in the model and know that which ever view the property is displayed, it won't be editable.

I thought I had the perfect solution, until I clicked save and get the error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

Using SQL profiler I have found that using the annotation [ReadOnly(true)] means that NULL will be sent to the database for saving.

Does anyone know why this happens, and is there anything I can do that will allow me to carry on in the way I think is a good solution for displaying data I don't want edited and controlling this in the Model.

Any other suggestions of achieving the same are welcome - or reasons why my whole design is flawed.

Upvotes: 1

Views: 1554

Answers (1)

Lucas L Roselli
Lucas L Roselli

Reputation: 2830

If you set the the property with ReadOnly when you press save the model binding will not get the value for readonly for a security reason, let's say if someone removes the readonly attribute through the developer console, then it will enable the field enabling edition, then it's not readonly anymore , that's why you are receiving null on the server ( model binding ), the right why it's to get the value of the readonly again on the server before persisting on the DB

in a few words, the readonly it's working fine as it should be

Upvotes: 2

Related Questions