locked
MVC 4 Not saving data after edit RRS feed

  • Question

  • User-835542053 posted

    Ran through the standard process of adding a new controller through VS 2011 Beta that automagically creates my index, create, edit, details, and delete views. I removed the 'DateCreated' field from the create view. Post version of create view works just fine and I set a 'DateCreated' field to DateTime.Now in my controller prior to saving the data to the database using the Entity Framework. I am then rerouted to the index view and I can see the 'DateCreated' field is populated just fine.

    I choose the Get version of edit and viewed the data returned from the database through setting a breakpoint and verified that the 'DateCreated' field is populated correctly. However, I do not display this data on the modified edit view.

    When I edit the data on the edit view and Post my changes, I see the 'DateCreated' field is set to null which then gets saved to my database as null. Arggg....

    Is there a setting somewhere to persist this data? What am I missing? Some fields I do not want shown on the edit view as I intend to set some of these values in my controller.

    Thanks for you help.

    Thursday, May 24, 2012 11:12 AM

Answers

  • User-1657171777 posted

    If you are using UpdateModel<T>, you may want to take advantage of the excludeProperties override parameter to omit DateCreated.

    Another option is to use @Html.HiddenFor(model => model.DateCreated) in your form.  This way, you don't display the value, but it still gets passed to your form's action.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 24, 2012 1:31 PM

All replies

  • User-1657171777 posted

    If you are using UpdateModel<T>, you may want to take advantage of the excludeProperties override parameter to omit DateCreated.

    Another option is to use @Html.HiddenFor(model => model.DateCreated) in your form.  This way, you don't display the value, but it still gets passed to your form's action.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 24, 2012 1:31 PM
  • User-835542053 posted

    I see. Works great with the Html.HiddenFor suggestion and that's probably what I'll stick with.

    Regarding the exclude properties... I have used [Exclude] on ids in my models to prevent them from being created in the templating process. I suppose I could just add [Exclude] to 'DateCreated' and still be able to use it for display purposes in the details view.

    Thanks for your help.

    Thursday, May 24, 2012 2:09 PM
  • User-1657171777 posted

    Any time, best of luck.

    Thursday, May 24, 2012 2:16 PM