1

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.

Community
  • 1
  • 1
Percy
  • 2,855
  • 2
  • 33
  • 56
  • you might be stuck transforming your type into a different type for the view purposes, then back to the DB type for storage purposes. – DLeh Mar 25 '15 at 20:00
  • or just use the accepted answer in that thread instead. `@Html.TextBoxFor(m => m.Property, new { @readonly="readonly" })` – DLeh Mar 25 '15 at 20:01
  • The accepted answer means that the controlling of editable and uneditable data is in the View - which I don't think follows the principles of MVC. Plus, when creating new views, I may forget to make it readonly (or another developer may not fully inderstand that it should be readonly) - but I accept that it is a solution - just not that great a solution. – Percy Mar 25 '15 at 20:07
  • well having objects that represent both your data model *and* your view model doesn't seem like a great practice either imo. – DLeh Mar 25 '15 at 20:08

1 Answers1

2

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

Lucas Roselli
  • 2,810
  • 1
  • 15
  • 18